demo需求:
1
2
3
4
5
6
7
|
(1)Properties類(lèi)加載.properties的方式 (2)dpcp連接池建立數(shù)據(jù)庫(kù)連接的方式 (3)查詢(xún)數(shù)據(jù)的方式 (4)靜態(tài)代碼塊的使用,分離驅(qū)動(dòng)的加載和連接信息的載入,整個(gè)服務(wù)器生命周期只執(zhí)行一次 |
demo所用jar包:
1
2
3
|
classes12.jar commons-dbcp-1.4.jar commons-pool-1.5.4.jar |
demo主要代碼展示:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
Utils.java private static Connection conn = null; private static BasicDataSource dataSource = new BasicDataSource(); private static Properties prop = getProperties("src/db.properties"); // 將連接池的創(chuàng)建放在靜態(tài)代碼塊,保證整個(gè)服務(wù)器生命周期只執(zhí)行一次,減少服務(wù)器負(fù)擔(dān) static { try { dataSource.setDriverClassName(prop.getProperty("driver")); dataSource.setUrl(prop.getProperty("url")); dataSource.setUsername(prop.getProperty("user")); dataSource.setPassword(prop.getProperty("password")); dataSource.setMaxActive(20); dataSource.setInitialSize(10); } catch (Exception e) { System.out.println("連接池創(chuàng)建失敗"); } } /** * show 方法簡(jiǎn)介 獲取數(shù)據(jù)庫(kù)連接池的連接,因?yàn)橐呀?jīng)封裝,以后只需要配置db.properties,無(wú)需動(dòng)這邊代碼 * * @author 葉灬黎 * @return */ public static Connection getConnection() { try { conn = dataSource.getConnection(); } catch (Exception e) { System.out.println("數(shù)據(jù)庫(kù)連接失敗"); } return conn; } /** * show 方法簡(jiǎn)介 讀取.properties文件,這里主要服務(wù)于想將jdbc連接數(shù)據(jù)庫(kù)的各項(xiàng)參數(shù)抽取出來(lái) * * @author 葉灬黎 * @param file * 要讀取的.properties文件的路徑 * @return Properties類(lèi)對(duì)象 */ private static Properties getProperties(String file) { Properties properties = new Properties(); try { FileInputStream fis = new FileInputStream(new File(file)); properties.load(fis); fis.close(); } catch (IOException e) { System.out.println("加載配置文件出錯(cuò)"); } return properties; } |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
|
OneSelect.java public static void main(String[] args) { List< String > names = new ArrayList<>(); try { Connection conn = Utils.getConnection(); //創(chuàng)建執(zhí)行引擎 Statement state = conn.createStatement(); //執(zhí)行sql String sql = "select * from emp"; ResultSet rs = state.executeQuery(sql); while(rs.next()){ names.add(rs.getString("ename")); } rs.close(); state.close(); conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(String s : names){ System.out.println(s); } } |
1
2
3
4
5
|
db.properties(src目錄下) driver = oracle.jdbc.driver.OracleDriver url = jdbc:oracle:thin:@127.0.0.1:1521:orcl user = scott password = 123456 |
demo資源位置:
1
|
svn://106.15.229.200/Javaweb/tinyDemo_jdbc 用戶(hù)temp/密碼temp) |
以上這篇jdbc結(jié)合dpcp連接池的封裝實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/yeli/archive/2017/10/26/7739308.html