1 package demo03; 2
3 import utils.JDBC_DBCP_Utils; 4
5 import javax.sql.DataSource; 6 import java.sql.Connection; 7 import java.sql.ParameterMetaData; 8 import java.sql.PreparedStatement; 9 import java.sql.SQLException; 10
11 public class MyJDBCTemplate { 12 //1. 需要傳入數據源
13 private DataSource dataSource; 14
15 //構造方法
16 public MyJDBCTemplate(DataSource dataSource) { 17 this.dataSource = dataSource; 18 } 19
20 /**
21 * 封裝了JDBC操作數據庫的步驟+元數據, 釋放資源(使用者不需要關注釋放資源了) 22 * 進行增,刪,修改 23 * 24 * @param sql sql語句 25 * @param params 參數 26 * @return Ctrl+Alt+T 27 */
28 public int update(String sql, Object... params) { 29 Connection connection = null; 30 PreparedStatement preparedStatement = null; 31 try { 32 //0. 非空判斷
33 if (dataSource == null) throw new RuntimeException("dataSource must not null..."); 34
35 if (sql == null) throw new RuntimeException("sql must not null..."); 36
37 //1. 從dataSource 獲得連接對象
38 connection = dataSource.getConnection(); 39 //2. 創建預編譯的sql語句對象 insert into user values (?,?,?,?)
40 preparedStatement = connection.prepareStatement(sql); 41
42 //3. 獲得參數的元數據對象
43 ParameterMetaData parameterMetaData = preparedStatement.getParameterMetaData(); 44 //4. 獲得參數的個數
45 int parameterCount = parameterMetaData.getParameterCount(); 46
47 //5. 給每一個?賦值
48 for (int i = 0; i < parameterCount; i++) { 49 preparedStatement.setObject(i + 1, params[i]); 50 } 51
52 //6. 執行
53 int i = preparedStatement.executeUpdate(); 54 return i; 55 } catch (SQLException e) { 56 e.printStackTrace(); 57 } finally { 58 //釋放資源
59 JDBC_DBCP_Utils.release(null, preparedStatement, connection); 60 } 61 return -1; 62 } 63 }