1. 程式人生 > 實用技巧 >關於Druid 連線池的使用方法

關於Druid 連線池的使用方法

根據個人學習進度分享出來的Druid連線池的使用方法,歡迎指正。

一、建立並修改 database.properties 檔案如下

driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/testjavadb?useSSL=false
username=root
password=root
#初始化連線
initialSize=10
#最大連線數
maxActive=50
#最小空閒連線
minIdle=5
#超時等待時間
maxWait=5000

二、建立並修改DruidUntils 相關連線池屬性及資料庫操作方法

public
class DruidUntils { // 建立連線物件 private static DruidDataSource dataSource; private static Connection connection; private static PreparedStatement pstmt = null; private static ResultSet resultSet = null; static { // 建立連線池 Properties properties = new Properties(); InputStream inputStream
= DruidUntils.class.getClassLoader().getResourceAsStream("database.properties"); try { properties.load(inputStream); System.out.println(properties); // 通過德魯伊連線池工廠建立一個連線池,自動解析properties檔案裡的鍵值對 dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); }
catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static DruidDataSource getDataSource() { return dataSource; }
  // 初始化連線池
  
public static Connection getConnection() { try { connection = dataSource.getConnection(); return connection; } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } /** * 查詢返回單條記錄,並儲存在map中 * * @param sql * @param params * @return * @throws SQLException */ public static Map<String, Object> findSimpleResult(String sql, List<Object> params) throws SQLException { Map<String, Object> map = new HashMap<String, Object>(); int index = 1; pstmt = (PreparedStatement) connection.prepareStatement(sql); System.out.println(pstmt); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery();// 返回查詢結果 // 獲取此 ResultSet 物件的列的編號、型別和屬性。 ResultSetMetaData metaData = resultSet.getMetaData(); int col_len = metaData.getColumnCount();// 獲取列的長度 while (resultSet.next())// 獲得列的名稱 { for (int i = 0; i < col_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null)// 列的值沒有時,設定列值為“” { cols_value = ""; } map.put(cols_name, cols_value); } } return map; } public static void closeAll() { try { if (resultSet != null) { resultSet.close(); } if (pstmt != null) { pstmt.close(); } if (connection != null) { connection.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * 完成對資料庫的表的新增刪除和修改的操作 * * @param sql * @param params * @return * @throws SQLException */ public boolean updateByPreparedStatement(String sql, List<Object> params) throws SQLException { boolean flag = false; int result = -1;// 表示當用戶執行新增刪除和修改的時候所影響資料庫的行數 pstmt = connection.prepareStatement(sql); int index = 1; // 填充sql語句中的佔位符 if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } result = pstmt.executeUpdate(); flag = result > 0 ? true : false; return flag; } /** * 查詢返回多行記錄,並儲存在List<Map<String, Object>>中 * * @param sql * @param params * @return * @throws SQLException */ public List<Map<String, Object>> findMoreResult(String sql, List<Object> params) throws SQLException { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } map.put(cols_name, cols_value); } list.add(map); } return list; } /** * jdbc的封裝可以用反射機制來封裝:取得單條記錄並儲存在javaBean中(這裡使用到了泛型) * * @param sql * @param params * @param cls * @return * @throws Exception */ public <T> T findSimpleRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { T resultObject = null; int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { // 通過反射機制建立例項 resultObject = cls.newInstance(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } // 返回一個 Field 物件,該物件反映此 Class 物件所表示的類或介面的指定已宣告欄位。 Field field = cls.getDeclaredField(cols_name); field.setAccessible(true);// 開啟javabean的訪問private許可權 field.set(resultObject, cols_value);// 為resultObject物件的field的屬性賦值 } } return resultObject; } /** * 通過反射機制訪問資料庫 jdbc的封裝可以用反射機制來封裝:取得多條記錄並儲存在javaBean的集合中中(這裡使用到了泛型) * * @param <T> * @param sql * @param params * @param cls * @return * @throws Exception */ public <T> List<T> findMoreRefResult(String sql, List<Object> params, Class<T> cls) throws Exception { List<T> list = new ArrayList<T>(); int index = 1; pstmt = connection.prepareStatement(sql); if (params != null && !params.isEmpty()) { for (int i = 0; i < params.size(); i++) { pstmt.setObject(index++, params.get(i)); } } resultSet = pstmt.executeQuery(); ResultSetMetaData metaData = resultSet.getMetaData(); int cols_len = metaData.getColumnCount(); while (resultSet.next()) { T resultObject = cls.newInstance(); for (int i = 0; i < cols_len; i++) { String cols_name = metaData.getColumnName(i + 1); Object cols_value = resultSet.getObject(cols_name); if (cols_value == null) { cols_value = ""; } Field field = cls.getDeclaredField(cols_name); field.setAccessible(true); field.set(resultObject, cols_value); } list.add(resultObject); } return list; } /** * 將連線引數寫入配置檔案 * * @param url * jdbc連線域名 * @param user * 使用者名稱 * @param password * 密碼 */ public static void writeProperties(String url, String user, String password) { Properties pro = new Properties(); FileOutputStream fileOut = null; try { fileOut = new FileOutputStream("Config.ini"); pro.put("url", url); pro.put("user", user); pro.put("password", password); pro.store(fileOut, "My Config"); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fileOut != null) fileOut.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 讀取配置檔案的連線引數 * * @return 返回list */ public static List readProperties() { List list = new ArrayList(); Properties pro = new Properties(); FileInputStream fileIn = null; try { fileIn = new FileInputStream("Config.ini"); pro.load(fileIn); list.add(pro.getProperty("url")); list.add(pro.getProperty("user")); list.add(pro.getProperty("password")); } catch (Exception e) { e.printStackTrace(); } finally { try { if (fileIn != null) fileIn.close(); } catch (IOException e) { e.printStackTrace(); } } return list; } }

三、建立外部使用檔案

public class UserDaoimpl {
    static Scanner sc = new Scanner(System.in);
    public static String sql = "select * from userlogin where username=? and password = ?";
    
    
    public static void main(String[] args) throws SQLException {
        // 初始化德魯伊池
        DruidUntils.getConnection();
        
        System.out.println("賬號:");
        String username = sc.next();
        System.out.println("密碼:");
        String password = sc.next();
        ArrayList<Object> list = new ArrayList<Object>();
        list.add(username);
        list.add(password);
        
        Map<String, Object> simpleMap = DruidUntils.findSimpleResult(sql,list);
        for (java.util.Map.Entry<String, Object> entry : simpleMap.entrySet()) {
                System.out.println(entry.getKey()+":"+ entry.getValue());
        }
        DruidUntils.closeAll();
    }
    
}

相關檔案包:

關於mysql-connector-java-5.1.45.jar包 資源下載

關於druid-1.1.22.jar包 資源下載