中阶d03.1 JDBCDemo
1. jdbc使用查看驱动的doc文档《connector-j.html》
2.代码实现:1. 注册驱动---2. 建立连接---3. 创建statement ,跟数据库打交道---
---4. 执行sql,得到ResultSet---5. 遍历结果 ---6. 释放资源
package zj_1_JDBC; import java.sql.*; public class MainTest { public static void main(String[] args) throws ClassNotFoundException { //注册驱动 Class.forName("com.mysql.jdbc.Driver"); //注册驱动这步可以写也可以不用写 String url = "jdbc:mysql://localhost/student"; String username = "root"; String password = "root"; Connection conn = null; Statement st = null; ResultSet rs = null; try {
//建立连接 conn = DriverManager.getConnection(url,username,password); // 创建statement st = conn.createStatement();//创建statement ,跟数据库打交道,一定需要这个对象 // 执行sql,得到ResultSet String sql = "SELECT * FROM users WHERE name = '小明'"; rs = st.executeQuery(sql); // 遍历结果 while (rs.next()) { //rs.next() 当读到行末尾时会返回false,下一行有数据则返回true int id = rs.getInt("id"); String name = rs.getString("name"); int age = rs.getInt("age"); System.out.println(id+""+name+","+age); } } catch (SQLException e) { e.printStackTrace(); }finally { // 释放资源 JDBCUtil.release(conn,st,rs); /* try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } try { st.close(); } catch (SQLException e) { e.printStackTrace(); } try { conn.close(); } catch (SQLException e) { e.printStackTrace(); }*/ } } }
工具类,整合释放资源方法
package zj_1_JDBC; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCUtil { Connection conn = null; Statement st = null; ResultSet rs = null; public static void release(Connection conn, Statement st, ResultSet rs) { closeRs(rs); closeSt(st); closeConn(conn); } private static void closeRs(ResultSet rs){ try { if(rs != null){ rs.close(); } } catch (SQLException e) { e.printStackTrace(); }finally{ rs = null; } } private static void closeSt(Statement st) { try { if(st != null) { st.close(); } } catch (SQLException e) { e.printStackTrace(); }finally { st = null; } } private static void closeConn(Connection conn) { try { if(conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); }finally { conn = null; } } }