標籤:source auth targe com attr lib type name copyto
資料來源:儲存了所有建立資料庫連接的資訊。就象通過指定檔案名稱你可以在檔案系統中找到檔案一樣,通過提供正確的資料來源名稱,你可以找到相應的資料庫連接。
1.JNDI方式建立DataSource
1.1 配置資料來源的相關串連資訊,該配置可以在Tomcat安裝目錄下的conf/context.xml檔案中配置。
其配置如下:
[html] view plain copy
- <Context>
- ……
- <!-- MySql -->
- <Resource name="jdbc/orclight" auth="Container"
-
- type="javax.sql.DataSource"maxActive="100" maxIdle="30"
-
- maxWait="10000"username="root" password="root"
-
- driverClassName="com.mysql.jdbc.Driver"
-
- url="jdbc:mysql://localhost:3306/orclight"/>
- ……
- </Context>
1.2 在程式中以JNDI的方式建立資料來源,得到資料庫連接已進行相應的操作
代碼如下:
[java] view plain copy
- / 初始化JNDI上下文,建立DataSource對象
-
- Context initContext = new InitialContext();
-
- Context context = (Context)initContext.lookup("java:comp/env");
-
- DataSourcedataSource = (DataSource)context.lookup("jdbc/orclight");
2.Apache提供的DBCP方式建立資料來源
2.1 以這種方式建立資料來源必須先準備兩個jar檔案:commons-dbcp.jar 和 commons-pool.jar。
2.2 以這種方式建立的資料來源就不再是javax.sql.DataSource。DataSource了,而是org.apache.commons.dbcp.BasicDataSource。
代碼如下:
[java] view plain copy
- // 建立BasicDataSource對象
-
- BasicDataSource ds = new BasicDataSource();
-
- ds.setDriverClassName("com.mysql.jdbc.Driver");
-
- ds.setUrl("jdbc:mysql://localhost:3306/orclight");
-
- ds.setUsername("root");
-
- ds.setPassword("root");
-
- ds.setInitialSize(50);
-
- ds.setMaxActive(100);
- ds.setMaxIdle(30);
- ds.setMaxWait(10000);
- // 關閉資料來源串連
- ds.close();
3.C3P0方式建立資料來源
3.1 使用C3P0方式建立資料來源應該首先準備一個jar檔案:c3p0-0.9.1.2.jar,將其放到web/lib目錄下,
就可以在項目中使用C3P0建立資料來源
3.2 3.2 C3P0建立的資料來源對象也不是DataSource對象,而是ComboPooledDataSource。
代碼如下:
[java] view plain copy
- // 建立ComboPooledDataSource對象
-
- ComboPooledDataSource ds = new ComboPooledDataSource();
-
- ds.setDriverClass("com.mysql.jdbc.Driver");
-
- ds.setJdbcUrl("jdbc:mysql://localhost:3306/orclight");
-
- ds.setUser("root");
-
- ds.setPassword("root");
-
- ds.setInitialPoolSize(50);
-
- ds.setMaxPoolSize(100);
-
- ds.setMaxIdleTime(10000);
Java 中常用的資料來源