1. 程式人生 > >Java 中常用的數據源

Java 中常用的數據源

tools xml文件 安裝目錄 建立數據庫 container word classname highlight attribute

數據源:存儲了所有建立數據庫連接的信息。就象通過指定文件名你可以在文件系統中找到文件一樣,通過提供正確的數據源名稱,你可以找到相應的數據庫連接。

1.JNDI方式創建DataSource

1.1 配置數據源的相關連接信息,該配置可以在Tomcat安裝目錄下的conf/context.xml文件中配置。
其配置如下:

[html] view plain copy
  1. <Context>
  2. ……
  3. <!-- MySql -->
  4. <Resource name="jdbc/orclight" auth="Container"
  5. type="javax.sql.DataSource"maxActive="100" maxIdle="30"
  6. maxWait="10000"username="root" password="root"
  7. driverClassName="com.mysql.jdbc.Driver"
  8. url="jdbc:mysql://localhost:3306/orclight"/>
  9. ……
  10. </Context>

1.2 在程序中以JNDI的方式創建數據源,得到數據庫連接已進行相應的操作

代碼如下:

[java] view plain copy
  1. / 初始化JNDI上下文,創建DataSource對象
  2. Context initContext = new InitialContext();
  3. Context context = (Context)initContext.lookup("java:comp/env");
  4. 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
  1. // 創建BasicDataSource對象
  2. BasicDataSource ds = new BasicDataSource();
  3. ds.setDriverClassName("com.mysql.jdbc.Driver");
  4. ds.setUrl("jdbc:mysql://localhost:3306/orclight");
  5. ds.setUsername("root");
  6. ds.setPassword("root");
  7. ds.setInitialSize(50);
  8. ds.setMaxActive(100);
  9. ds.setMaxIdle(30);
  10. ds.setMaxWait(10000);
  11. // 關閉數據源連接
  12. 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
    1. // 創建ComboPooledDataSource對象
    2. ComboPooledDataSource ds = new ComboPooledDataSource();
    3. ds.setDriverClass("com.mysql.jdbc.Driver");
    4. ds.setJdbcUrl("jdbc:mysql://localhost:3306/orclight");
    5. ds.setUser("root");
    6. ds.setPassword("root");
    7. ds.setInitialPoolSize(50);
    8. ds.setMaxPoolSize(100);
    9. ds.setMaxIdleTime(10000);

Java 中常用的數據源