一、步骤介绍
1.通过Class.forName()加载驱动;
2.通过DriverManager.getConnection()获取Conncetion连接对象;
3.创建Statement对象传递sql语句到数据库执行;
4.接收ResultSet查询结果;
5.释放资源。
二、查询案例
public void getData(){ String URL = "jdbc:sqlserver://127.0.0.1:1433;databaseName=news"; Connection con = null;
Statement statement = null;
ResultSet rs = null; try { // 加载驱动 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // 获得数据库连接对象 con = DriverManager.getConnection(URL, "sa", "12345yehuan"); // 执行sql语句 String sql = "select * from student"; statement = con.createStatement();
// 接收查询结果 rs = statement.executeQuery(sql); while(rs.next()){ int id = rs.getInt(1); String name = rs.getString(2); int age = rs.getInt(3); System.out.println(id+" "+name+" "+age); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try {
// 释放资源
rs.close();
statement.close(); con.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
sqlserver jar包下载
https://pan.baidu.com/s/19SkEac-Lekw6tXye5kVB-Q
密码:6p1y