Java 中常用的數據源
阿新 • • 發佈:2017-07-05
tools xml文件 安裝目錄 建立數據庫 container word classname highlight attribute
數據源:存儲了所有建立數據庫連接的信息。就象通過指定文件名你可以在文件系統中找到文件一樣,通過提供正確的數據源名稱,你可以找到相應的數據庫連接。
1.JNDI方式創建DataSource
1.1 配置數據源的相關連接信息,該配置可以在Tomcat安裝目錄下的conf/context.xml文件中配置。
其配置如下:
- <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 中常用的數據源