Java 中常用的數據源


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

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.   
  6.            type="javax.sql.DataSource"maxActive="100" maxIdle="30"  
  7.   
  8.            maxWait="10000"username="root" password="root"  
  9.   
  10.            driverClassName="com.mysql.jdbc.Driver"  
  11.   
  12.            url="jdbc:mysql://localhost:3306/orclight"/>  
  13.     ……  
  14. </Context>  

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

代碼如下:      

 

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM