DBUtil工具
DBUtil:
DBUtils 是一個jdbc的工具,使用的范圍內非常廣,主要是為了簡化jdbc的代碼
核心類:QueryRunner; ResultSetHandler
核心方法:
- update();用來執行DDL(DDL:create alert,drop;);
- query();用來執行DML(DML:insert update delete;);
- batch(); 用來執行批處理;
- 調用本方法之前,需要先創建對象,代碼如下:
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{@Overridepublic 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工具類實現刪除功能:
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");}} }總結
- 上一篇: sql语句按月份统计查询
- 下一篇: HDFS命令