前言
日常開發中,我們都習慣了使用ORM框架來幫我們操作數據庫,本文復習、記錄Java如何使用原生JDBC操作數據庫
代碼編寫
封裝幾個簡單方法
find查詢方法
findOne查詢方法
execute執行方法
package cn.huanzi.qch.util; import java.sql.*; import java.util.ArrayList; import java.util.HashMap; /** * 原生jdbc操作數據庫工具類 * https://www.cnblogs.com/huanzi-qch/p/15474928.html */ public class DbUtil { //數據庫連接:地址、用戶名、密碼 private final String url; private final String username; private final String password; //Connection連接實例 private Connection connection; public DbUtil(String url, String username, String password){ this.url = url; this.username = username; this.password = password; } public DbUtil(String url, String username, String password, String driver){ this(url,username,password); //加載驅動 try { /* 同時需要引入相關驅動依賴 1、MySQL: com.mysql.cj.jdbc.Driver 2、Oracle: oracle.jdbc.driver.OracleDriver 3、pgsql: org.postgresql.Driver */ Class.forName(driver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 獲取 Connection 連接 */ private Connection getConnection() { if(connection == null){ try { connection= DriverManager.getConnection(url, username, password); connection.setAutoCommit(true); } catch (SQLException e) { System.err.println("獲取Connection連接異常..."); e.printStackTrace(); } } return connection; } /** * 設置是否自動提交事務 * 當需要進行批量帶事務的操作時,關閉自動提交手動管理事務,將會大大提高效率! */ public void setAutoCommit(boolean autoCommit){ try { this.getConnection().setAutoCommit(autoCommit); } catch (SQLException e) { e.printStackTrace(); } } /** * 關閉自動提交事務時,需要手動管理事務提交、回滾 */ public void commit(){ try { this.getConnection().commit(); } catch (SQLException e) { e.printStackTrace(); } } public void rollback(){ try { this.getConnection().rollback(); } catch (SQLException e) { e.printStackTrace(); } } /** * 關閉 Connection 連接 */ public void close(){ if(connection != null){ try { connection.close(); connection = null; } catch (SQLException e) { System.err.println("關閉Connection連接異常..."); e.printStackTrace(); } } } /** * 查詢 * 查詢語句 */ public ArrayList<HashMap<String,Object>> find(String sql, Object[] params) { ArrayList<HashMap<String, Object>> list = new ArrayList<>(); //獲取連接 Connection conn = this.getConnection(); PreparedStatement ps; ResultSet rs; try { //設置SQL、以及參數 ps = conn.prepareStatement(sql); if (params != null) { for (int i = 0; i < params.length; i++) { ps.setObject(i + 1, params[i]); } } //執行查詢 rs = ps.executeQuery(); //獲取查詢結果 ResultSetMetaData rm = rs.getMetaData(); int columnCount = rm.getColumnCount(); //封裝結果集 while (rs.next()) { HashMap<String, Object> map = new HashMap<>(columnCount); for (int i = 1; i <= columnCount; i++) { String name = rm.getColumnName(i).toLowerCase(); Object value = rs.getObject(i); map.put(name,value); } list.add(map); } } catch (Exception e) { System.err.println("執行 jdbcUtil.find() 異常..."); e.printStackTrace(); } return list; } public HashMap<String,Object> findOne(String sql, Object[] params){ ArrayList<HashMap<String, Object>> list = this.find(sql, params); return list.size() > 0 ? list.get(0) : null; } public ArrayList<HashMap<String,Object>> find(String sql) { return this.find(sql,null); } public HashMap<String,Object> findOne(String sql) { return this.findOne(sql,null); } /** * 執行 * 新增/刪除/更新 等SQL語句 */ public boolean execute(String sql, Object[] params){ boolean flag = false; //獲取連接 Connection conn = this.getConnection(); PreparedStatement ps; try { //設置SQL、以及參數 ps = conn.prepareStatement(sql); if (params != null) { for (int i = 0; i < params.length; i++) { ps.setObject(i + 1, params[i]); } } //執行 //如果第一個結果是ResultSet 象,則返回 true; //如果第一個結果是更新計數或者沒有結果,則返回 false; flag = ps.execute(); } catch (SQLException e) { System.err.println("執行 jdbcUtil.update() 異常..."); e.printStackTrace(); } return flag; } public boolean execute(String sql){ return this.execute(sql,null); } }
效果
運行main函數
public static void main(String[] args) { //獲取實例 DbUtil dbUtil = new DbUtil("jdbc:mysql://localhost/jfinal_demo","root","123456"); // find查詢 ArrayList<HashMap<String, Object>> list = dbUtil.find("select * from user"); for (HashMap<String, Object> map : list) { System.out.println(map); } System.out.println("----------------------------"); //execute執行、findOne查詢 dbUtil.execute("delete from user where user_id = ?", new Object[]{"4"}); dbUtil.execute("insert into user values (?,?)", new Object[]{"4","王麻子"}); dbUtil.execute("update user set user_name = ? where user_id = ?", new Object[]{"王麻子子","4"}); HashMap<String, Object> map = dbUtil.findOne("select * from user where user_id = ?", new Object[]{"4"}); System.out.println(map); //關閉連接 dbUtil.close(); }
后記
原生JDBC操作數據庫暫時先記錄到這,后續再進行補充
PS:當需要進行批量帶事務的操作時,將自動提交改成false,然后手動管理,將會大大提高效率!