demo需求:
1
2
3
4
5
6
7
|
(1)Properties類加載.properties的方式 (2)dpcp連接池建立數據庫連接的方式 (3)查詢數據的方式 (4)靜態代碼塊的使用,分離驅動的加載和連接信息的載入,整個服務器生命周期只執行一次 |
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"); // 將連接池的創建放在靜態代碼塊,保證整個服務器生命周期只執行一次,減少服務器負擔 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("連接池創建失敗"); } } /** * show 方法簡介 獲取數據庫連接池的連接,因為已經封裝,以后只需要配置db.properties,無需動這邊代碼 * * @author 葉灬黎 * @return */ public static Connection getConnection() { try { conn = dataSource.getConnection(); } catch (Exception e) { System.out.println("數據庫連接失敗"); } return conn; } /** * show 方法簡介 讀取.properties文件,這里主要服務于想將jdbc連接數據庫的各項參數抽取出來 * * @author 葉灬黎 * @param file * 要讀取的.properties文件的路徑 * @return Properties類對象 */ 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("加載配置文件出錯"); } 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(); //創建執行引擎 Statement state = conn.createStatement(); //執行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 用戶temp/密碼temp) |
以上這篇jdbc結合dpcp連接池的封裝實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/yeli/archive/2017/10/26/7739308.html