commons-dbutils 是 Apache 組織提供的一個開源 JDBC工具類庫,它是對JDBC的簡單封裝,學習成本極低,並且使用dbutils能極大簡化jdbc編碼的工作量,同時也不會影響程序的性能。因此dbutils成為很多不喜歡hibernate的公司的首選。
commons-dbutilsAPI介紹:
- org.apache.commons.dbutils.QueryRunner
- org.apache.commons.dbutils.ResultSetHandler
工具類
- org.apache.commons.dbutils.DbUtils
直接上代碼:
1.先建立一個jdbc的連接相關類:
1 package com.ming.core.db; 2 3 import java.io.InputStream; 4 import java.io.PrintWriter; 5 import java.sql.Connection; 6 import java.sql.DriverManager; 7 import java.sql.PreparedStatement; 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 import java.sql.SQLFeatureNotSupportedException; 11 import java.sql.Statement; 12 import java.util.Properties; 13 import java.util.logging.Logger; 14 15 import javax.sql.DataSource; 16 17 import org.apache.commons.dbutils.ResultSetHandler; 18 19 public class JdbcUtils { 20 21 private static String driver = "com.mysql.jdbc.Driver"; 22 private static String url = "jdbc:mysql://localhost:3306/test"; 23 private static String username = "root"; 24 private static String password = "root"; 25 static { 26 try { 27 // 加載數據庫驅動 28 Class.forName(driver); 29 } catch (Exception e) { 30 throw new ExceptionInInitializerError(e); 31 } 32 } 33 34 /** 35 * @Method: getConnection 36 * @Description: 獲取數據庫連接對象 37 * @Anthor:孤傲蒼狼 38 * 39 * @return Connection數據庫連接對象 40 * @throws SQLException 41 */ 42 public static Connection getConnection() throws SQLException { 43 return DriverManager.getConnection(url, username, password); 44 } 45 46 /** 47 * @Method: release 48 * @Description: 釋放資源, 要釋放的資源包括Connection數據庫連接對象,負責執行SQL命令的Statement對象, 49 * 存儲查詢結果的ResultSet對象 50 * @Anthor:孤傲蒼狼 51 * 52 * @param conn 53 * @param st 54 * @param rs 55 */ 56 public static void release(Connection conn, Statement st, ResultSet rs) { 57 if (rs != null) { 58 try { 59 // 關閉存儲查詢結果的ResultSet對象 60 rs.close(); 61 } catch (Exception e) { 62 e.printStackTrace(); 63 } 64 rs = null; 65 } 66 if (st != null) { 67 try { 68 // 關閉負責執行SQL命令的Statement對象 69 st.close(); 70 } catch (Exception e) { 71 e.printStackTrace(); 72 } 73 } 74 75 if (conn != null) { 76 try { 77 // 關閉Connection數據庫連接對象 78 conn.close(); 79 } catch (Exception e) { 80 e.printStackTrace(); 81 } 82 } 83 } 84 85 /** 86 * @Method: update 87 * @Description: 萬能更新 所有實體的CUD操作代碼基本相同,僅僅發送給數據庫的SQL語句不同而已, 88 * 因此可以把CUD操作的所有相同代碼抽取到工具類的一個update方法中,並定義參數接收變化的SQL語句 89 * @Anthor:孤傲蒼狼 90 * @param sql 91 * 要執行的SQL 92 * @param params 93 * 執行SQL時使用的參數 94 * @throws SQLException 95 */ 96 public static void update(String sql, Object params[]) throws SQLException { 97 Connection conn = null; 98 PreparedStatement st = null; 99 ResultSet rs = null; 100 try { 101 conn = getConnection(); 102 st = conn.prepareStatement(sql); 103 for (int i = 0; i < params.length; i++) { 104 st.setObject(i + 1, params[i]); 105 } 106 st.executeUpdate(); 107 108 } finally { 109 release(conn, st, rs); 110 } 111 } 112 113 /** 114 * @Method: query 115 * @Description:萬能查詢 實體的R操作,除SQL語句不同之外,根據操作的實體不同,對ResultSet的映射也各不相同, 116 * 因此可義一個query方法,除以參數形式接收變化的SQL語句外, 117 * 可以使用策略模式由qurey方法的調用者決定如何把ResultSet中的數據映射到實體對象中。 118 * @Anthor:孤傲蒼狼 119 * 120 * @param sql 121 * 要執行的SQL 122 * @param params 123 * 執行SQL時使用的參數 124 * @param rsh 125 * 查詢返回的結果集處理器 126 * @return 127 * @throws SQLException 128 */ 129 public static Object query(String sql, Object params[], ResultSetHandler rsh) throws SQLException { 130 131 Connection conn = null; 132 PreparedStatement st = null; 133 ResultSet rs = null; 134 135 try { 136 conn = getConnection(); 137 st = conn.prepareStatement(sql); 138 for (int i = 0; i < params.length; i++) { 139 st.setObject(i + 1, params[i]); 140 } 141 rs = st.executeQuery(); 142 /** 143 * 對於查詢返回的結果集處理使用到了策略模式, 144 * 在設計query方法時,query方法事先是無法知道用戶對返回的查詢結果集如何進行處理的,即不知道結果集的處理策略, 145 * 那么這個結果集的處理策略就讓用戶自己提供,query方法內部就調用用戶提交的結果集處理策略進行處理 146 * 為了能夠讓用戶提供結果集的處理策略,需要對用戶暴露出一個結果集處理接口ResultSetHandler 147 * 用戶只要實現了ResultSetHandler接口,那么query方法內部就知道用戶要如何處理結果集了 148 */ 149 return rsh.handle(rs); 150 151 } finally { 152 release(conn, st, rs); 153 } 154 } 155 156 public static DataSource getDataSource(){ 157 return new DataSource() { 158 159 160 @Override 161 public Connection getConnection(String username, String password) throws SQLException { 162 163 return null; 164 } 165 166 @Override 167 public Connection getConnection() throws SQLException { 168 169 return JdbcUtils.getConnection(); 170 } 171 172 @Override 173 public PrintWriter getLogWriter() throws SQLException { 174 175 return null; 176 } 177 178 @Override 179 public int getLoginTimeout() throws SQLException { 180 181 return 0; 182 } 183 184 @Override 185 public Logger getParentLogger() throws SQLFeatureNotSupportedException { 186 187 return null; 188 } 189 190 @Override 191 public void setLogWriter(PrintWriter out) throws SQLException { 192 193 194 } 195 196 @Override 197 public void setLoginTimeout(int seconds) throws SQLException { 198 199 200 } 201 202 @Override 203 public boolean isWrapperFor(Class<?> iface) throws SQLException { 204 205 return false; 206 } 207 208 @Override 209 public <T> T unwrap(Class<T> iface) throws SQLException { 210 211 return null; 212 } 213 }; 214 } 215 }
2.建立一個與數據相關的實體類
1 package com.ming.user.entity; 2 3 public class User { 4 5 private int id; 6 7 private String account; 8 9 private int user_id; 10 11 public int getId() { 12 return id; 13 } 14 15 public void setId(int id) { 16 this.id = id; 17 } 18 19 public String getAccount() { 20 return account; 21 } 22 23 public void setAccount(String account) { 24 this.account = account; 25 } 26 27 public int getUser_id() { 28 return user_id; 29 } 30 31 public void setUser_id(int user_id) { 32 this.user_id = user_id; 33 } 34 35 36 }
3.數據庫操作類及測試方法
1 package com.ming.core.db; 2 3 import java.sql.SQLException; 4 import java.util.List; 5 6 7 import org.apache.commons.dbutils.QueryRunner; 8 import org.apache.commons.dbutils.handlers.BeanHandler; 9 import org.apache.commons.dbutils.handlers.BeanListHandler; 10 11 import com.ming.user.entity.User; 12 13 public class QueryRunnerCRUDTest { 14 15 /* 16 *測試表 17 CREATE TABLE `users` ( 18 `id` BIGINT(20) NOT NULL AUTO_INCREMENT, 19 `account` VARCHAR(50) NULL DEFAULT NULL, 20 `user_id` BIGINT(20) NOT NULL, 21 PRIMARY KEY (`id`) 22 ) 23 COMMENT='user表' 24 COLLATE='latin1_swedish_ci' 25 ENGINE=InnoDB 26 ; 27 */ 28 29 30 public void add() throws SQLException { 31 //將數據源傳遞給QueryRunner,QueryRunner內部通過數據源獲取數據庫連接 32 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); 33 String sql = "INSERT INTO `test`.`users` (`account`, `user_id`) VALUES (?, ?);"; 34 Object params[] = {"hello world",2323}; 35 36 qr.update(sql, params); 37 } 38 39 40 41 public void delete() throws SQLException { 42 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); 43 String sql = "delete from users where id=?"; 44 qr.update(sql, 1); 45 46 } 47 48 49 public void update() throws SQLException { 50 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); 51 String sql = "update users set account=? where id=?"; 52 Object params[] = { "ddd", 2}; 53 qr.update(sql, params); 54 } 55 56 57 public void find() throws SQLException { 58 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); 59 String sql = "select * from users where id=?"; 60 Object params[] = {2}; 61 User user = (User) qr.query(sql, params, new BeanHandler(User.class)); 62 System.out.println(user.getId()); 63 } 64 65 66 public void getAll() throws SQLException { 67 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); 68 String sql = "select * from users"; 69 List<User> list = (List<User>) qr.query(sql, new BeanListHandler(User.class)); 70 for(User u : list){ 71 System.out.println(u.getUser_id()); 72 } 73 74 } 75 76 public void testBatch() throws SQLException { 77 QueryRunner qr = new QueryRunner(JdbcUtils.getDataSource()); 78 String sql = "INSERT INTO `test`.`users` (`account`, `user_id`) VALUES (?, ?)"; 79 Object params[][] = new Object[10][]; 80 for (int i = 0; i < 10; i++) { 81 params[i] = new Object[] {"123"+i, i}; 82 } 83 qr.batch(sql, params); 84 } 85 86 public static void main(String[] args) throws Exception { 87 QueryRunnerCRUDTest t=new QueryRunnerCRUDTest(); 88 t.add(); 89 t.find(); 90 t.delete(); 91 } 92 93 94 }
以上代碼都測試通了。
該博客參考:http://www.cnblogs.com/xdp-gacl/p/4007225.html