笔记|DBUtil工具

DBUtil:
DBUtils 是一个jdbc的工具,使用的范围内非常广,主要是为了简化jdbc的代码
核心类:QueryRunner; ResultSetHandler
核心方法:

  • update(); 用来执行DDL(DDL:create alert,drop; );
  • query(); 用来执行DML(DML:insert update delete; );
  • batch(); 用来执行批处理;
  • 调用本方法之前,需要先创建对象,代码如下:
QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

DBUtil工具类的创建:
//创建一个接口以实现查询功能 interface IRowMapper{ void rowMapper(ResultSet res); }public class DBUtil { //因为加载驱动的代码只需要执行一次即可,没必要重复执行,所以封装到静态代码块中 static { try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //将建立连接的代码抽取出来,提高代码的复用性 private static Connection getConnection() { try { return DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "0314"); } catch (SQLException e) { e.printStackTrace(); } return null; } //实现查询功能 public static void select(String sql, IRowMapper rowMapper) { Connection connection = null; Statement statement = null; ResultSet result = null; try { connection = getConnection(); statement = connection.createStatement(); result = statement.executeQuery(sql); rowMapper.rowMapper(result); } catch (Exception e) { e.printStackTrace(); }finally { close(result, statement, connection); } } //实现增删改功能 public static boolean update(String sql) {Connection connection = null; Statement statement = null; try { connection = getConnection(); statement = connection.createStatement(); return statement.executeUpdate(sql) > 0; } catch (Exception e) { e.printStackTrace(); }finally { close(statement, connection); } return false; } //将关闭资源代码抽取出来,提高代码的复用性 private static void close(Statement statement, Connection connection) { try { if (statement != null) { statement.close(); } } catch (SQLException e) { e.printStackTrace(); }try { if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } //close方法的重载 private static void close(ResultSet result, Statement statement, Connection connection) { try { if (result != null) { result.close(); } result = null; } catch (SQLException e) { e.printStackTrace(); } close(statement, connection); } }

DBUtil工具类的使用:
public class Select { public static void main(String[] args){ String sql = "select * from user_info"; class RowMapper implements IRowMapper{ @Override public void rowMapper(ResultSet res) { try { while (res.next()) { String student_id = res.getString("id"); String userName = res.getString("user_name"); String password = res.getString("password"); System.out.println(student_id+" ,"+userName+" ,"+password); } } catch (SQLException e) { e.printStackTrace(); } } } IRowMapper rowMapper = new RowMapper(); DBUtil.select(sql, rowMapper); } }

【笔记|DBUtil工具】使用DBUtil工具类实现删除功能:
public class Update { public static void main(String[] args) {String sql = "delete from user_info"; if (DBUtil.update(sql)) { System.out.println("YSE"); }else { System.out.println("NO"); } } }

    推荐阅读