1. 程式人生 > >Java中Dao模式中Dao的數據庫操作(BaseDao的寫法)

Java中Dao模式中Dao的數據庫操作(BaseDao的寫法)

nec roo sql rac 127.0.0.1 關閉 ron [] cnblogs

Dao模式是Java面向設計時的一種模式。而Dao中的BaseDao無非是對數據進行CURD(增刪改查),下面是最常用的連接,增刪改查的方法。

  1 package dao;
  2 
  3 import java.sql.*;
  4 
  5 /**
  6  * 數據庫訪問類
  7  */
  8 public class BaseDao {
  9     //數據庫驅動
 10     private static String driver = "com.mysql.jdbc.Driver";
 11     //數據庫連接地址
 12     private
static String url = "jdbc:mysql://127.0.0.1:3306/flight?useSSL=False"; 13 //數據庫用戶名 14 private static String user = "root"; 15 //數據庫密碼 16 private static String password = "123456"; 17 18 //數據庫連接 19 protected Connection conn = null; 20 //statement對象 21 protected PreparedStatement pstmt = null
; 22 23 /** 24 * 連接數據庫 25 * 26 * @return 數據庫連接 27 * @throws ClassNotFoundException 未找到驅動類異常 28 * @throws SQLException 數據庫異常 29 */ 30 protected Connection getConn() throws ClassNotFoundException, SQLException { 31 //加載驅動 32 Class.forName(driver);
33 //獲取連接 34 conn = DriverManager.getConnection(url, user, password); 35 return conn; 36 } 37 38 /** 39 * 數據庫查詢方法 40 * 41 * @param sql 預編譯sql語句 42 * @param params 預編譯參數 43 * @return 查詢結果集 44 * @throws SQLException 數據庫異常 45 */ 46 protected ResultSet executeQuerySQL(String sql, Object[] params) throws SQLException { 47 ResultSet rs = null; 48 try { 49 conn = getConn(); 50 } catch (ClassNotFoundException e) { 51 e.printStackTrace(); 52 } 53 pstmt = conn.prepareStatement(sql); 54 if (params != null) { 55 for (int i = 0; i < params.length; i++) { 56 pstmt.setObject(i + 1, params[i]); 57 } 58 } 59 rs = pstmt.executeQuery(); 60 return rs; 61 } 62 63 /** 64 * 數據庫增刪改方法 65 * 66 * @param sql 預編譯sql語句 67 * @param params 預編譯參數 68 * @return 數據庫影響行數 69 * @throws SQLException 數據庫異常 70 */ 71 protected int executeUpdate(String sql, Object[] params) throws SQLException { 72 try { 73 conn = getConn(); 74 } catch (ClassNotFoundException e) { 75 e.printStackTrace(); 76 } 77 int num = 0; 78 pstmt = conn.prepareStatement(sql); 79 if (params != null) { 80 for (int i = 0; i < params.length; i++) { 81 pstmt.setObject(i + 1, params[i]); 82 } 83 } 84 num = pstmt.executeUpdate(); 85 86 return num; 87 } 88 89 /** 90 * 關閉數據庫連接 91 * @param conn 數據庫連接 92 * @param pstmt statement對象 93 * @param rs ResultSet對象 94 */ 95 protected void closeALL(Connection conn, PreparedStatement pstmt, ResultSet rs) { 96 try { 97 if (rs != null) { 98 rs.close(); 99 } 100 if (pstmt != null) { 101 pstmt.close(); 102 } 103 if (conn != null) { 104 conn.close(); 105 } 106 } catch (SQLException e) { 107 e.printStackTrace(); 108 } 109 } 110 }

Java中Dao模式中Dao的數據庫操作(BaseDao的寫法)