码迷,mamicode.com
首页 > 数据库 > 详细

java eclipse 连接数据库全过程

时间:2016-06-27 10:26:28      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:

1、需要下载一个jar包。地址 http://pan.baidu.com/s/1i50LRId

2、代码如下:

import java.sql.*;

public class Mytest {
    public static void main(String[] args){
        String sql = "select * from student";

        String url = "jdbc:sqlserver://WANGHONGHONG-PC\\SQLSERVER2;DatabaseName=hh";
        String username = "sa";
        String password = "sa@12345";

        Connection conn;
        Statement stmt;
        ResultSet rs;
        try {
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();

          conn = DriverManager.getConnection(url, username, password);
          stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
          rs = stmt.executeQuery(sql);

          System.out.println(rs.next());

          rs.close();
          stmt.close();
          conn.close();

        } catch (InstantiationException e) {
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        } catch (SQLException e) {
          e.printStackTrace();
        }

      }
}

3、效果:

技术分享

4、又完善一版(添加输出)

import java.sql.*;

public class Mytest {
    public static void main(String[] args){
        String sql = "select * from student";

        String url = "jdbc:sqlserver://WANGHONGHONG-PC\\SQLSERVER2;DatabaseName=hh";
        String username = "sa";
        String password = "sa@12345";

        Connection conn;
        Statement stmt;
        ResultSet rs;
        try {
          Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();

          conn = DriverManager.getConnection(url, username, password);
          stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
          rs = stmt.executeQuery(sql);

          while(rs.next()){
          System.out.println(rs.getString("name"));
          }
          rs.close();
          stmt.close();
          conn.close();

        } catch (InstantiationException e) {
          e.printStackTrace();
        } catch (IllegalAccessException e) {
          e.printStackTrace();
        } catch (ClassNotFoundException e) {
          e.printStackTrace();
        } catch (SQLException e) {
          e.printStackTrace();
        }

      }
}

 

请各位大神们指点一二

java eclipse 连接数据库全过程

标签:

原文地址:http://www.cnblogs.com/honghong75042/p/5619185.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!