druid資料庫連線池DateSource和Apache.DBUtils的工具類使用QueryRunner
阿新 • • 發佈:2020-12-18
技術標籤:Mysql
配置檔案
通過配置檔案去配置連線
屬性和欄位名不一致
通過反射發現實體類屬性和資料庫欄位名不一致時,通過配置檔案去設定userName=user_name,相對應後再通過配置檔案去得到結果集中的值
資料來源DataSource連線池druid
原因:
資料庫連線非常的耗費資源,連線建立後使用完就關閉,下一次連線又需要建立,耗費資源
好處:
使用連線池進行建立,可以只建立一次,然後從池中獲取連線,節省伺服器資源和時間
所有連線統一進行管理
連線池的使用:
匯入jar包
建立配置檔案注意配置檔案的名字
初始化連線池
使用連線時直接從連線池中獲取連線
#連線設定
driverClassName= com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/school
username=root
password=123456
如果連線池的空閒連線大於最小連線,直接取連線操作接數
如果連線池中空閒連線小於最小連線數,自動增加連線,但不能大於最大連
#<!-- 初始化連線 -->
initialSize=10
#最大連線數量
maxActive=50
#<!-- 最小空閒連線 -->
minIdle=5
#<!-- 超時等待時間以毫秒為單位 60000毫秒/1000等於60秒 -->
<!如果連線池中空閒連線小於最小連線數,但是連線數量已經達到最大連線數,則讓使用者等待指定時間,在此時間內,若有連線返回到連線池中,則直接使用,如果沒有連線返回池中,超過時間後報一個連線不夠的異常>
maxWait=5000
public static DruidDataSource druidDS;
public static ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
public static Connection getConnection() throws Exception {
if (threadLocal.get()==null){
Properties p=new Properties();
p. load(new FileInputStream("u.properties"));
druidDS= (DruidDataSource) DruidDataSourceFactory.createDataSource(p);
DruidPooledConnection connection1 = druidDS.getConnection();
// Class.forName(p.getProperty("driverClass"));
// String url=p.getProperty("url");
// String username=p.getProperty("user");
// String password=p.getProperty("password");
// Connection connection= DriverManager.getConnection(url,username,password);
threadLocal.set(connection1);
}else {
return threadLocal.get();
}
return threadLocal.get();
}
Apache封裝的工具類
19.1.1 apache的DbUtils主要包含
事務控制需要自己控制
- ResultSetHandler介面:轉換型別介面
- BeanHandler類:實現類,把一條記錄轉換成物件
- BeanListHandler類:實現類,把多條記錄轉換成List集合。
- ScalarHandler類:實現類,適合獲取一行一列的資料。
- QueryRunner:執行sql語句的類
- 增、刪、改:update();
- 查詢:query();
- 實現:
導包
連線配置檔案
//裡面是個datasource
QueryRunner queryRunner=new QueryRunner(DBUtils.druidDS);
Account query = queryRunner.query("select * from t_account where name=?", new BeanHandler<Account>(Account.class), "ls");
System.out.println(query);