DBUtils之連線池
阿新 • • 發佈:2018-12-05
為減小系統對資料庫的獲取連線和關閉連線的開銷,連線池便是一個不錯的選擇
- 將DataSource封裝成一個工具類,使用時呼叫即可
package com.kong.JDBCUtils; import org.apache.commons.dbcp.BasicDataSource; import javax.sql.DataSource; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * 使用了properties+連線池; * 推薦使用此類獲取dataSource方法 */ public class JDBCUtils { private static BasicDataSource basicDataSource = new BasicDataSource(); private static String driverName; private static String url; private static String username; private static String password; static{ InputStream inputStream = JDBCUtils.class.getClassLoader().getResourceAsStream("database.properties"); Properties properties = new Properties(); try { properties.load(inputStream); } catch (IOException e) { throw new RuntimeException(e+"讀取配置檔案失敗"); } driverName = properties.getProperty("driver"); url = properties.getProperty("url"); username = properties.getProperty("name"); password = properties.getProperty("password"); //設定DataSource基本資訊 basicDataSource.setDriverClassName(driverName); basicDataSource.setUrl(url); basicDataSource.setUsername(username); basicDataSource.setPassword(password); //設定DataSource其他連線資訊 basicDataSource.setInitialSize(10);//初始化的連線數 basicDataSource.setMaxActive(8);//最大的連線數 basicDataSource.setMaxIdle(5);//最大空閒數 basicDataSource.setMinIdle(1);//最小空閒數 } public static DataSource getbasicDataSource(){ return basicDataSource; } }
- 呼叫
public class DBUtilsLinkDemo { public static void main(String[] args) throws IOException { try { Connection connection = JDBCUtils.getbasicDataSource().getConnection(); System.out.println(connection); } catch (SQLException e) { throw new RuntimeException(e+"database connect fail"); } } }
- 結果
^_^