java eclipse 连接数据库全过程

Posted 光阴易逝,岂容我待

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java eclipse 连接数据库全过程相关的知识,希望对你有一定的参考价值。

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 连接数据库全过程的主要内容,如果未能解决你的问题,请参考以下文章

Java调用MySQL存储过程

eclipse(Java)对MySQL数据库进行连接查询和修改

怎么在eclipse中使用数据库连接

Eclipse 中的通用代码片段或模板

xml Eclipse模板(代码片段)检查参数并最终抛出IllegalArgumentException

部分代码片段