c3p0串連資料庫的3種方式,

來源:互聯網
上載者:User

c3p0串連資料庫的3種方式,

c3p0串連資料庫的3種方式,這裡以mysql為例

1. 直接用set方法設定參數, 基本方法

ComboPooledDataSource dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUser("root");
dataSource.setPassword("asd");

調用的時候只需要在QueryRunner的構造方法裡引用dataSource(以dbutils為例), 就像這樣:

 QueryRunner qr = new QueryRunner(dataSource); 


當然也可以用dataSource擷取一個串連, 像這樣:

   Connection conn = dataSource.getConnection(); 

  然後查詢的時候調用QueryRunner的無參建構函式, 像這樣:

  QueryRunner qr = new QueryRunner();

  然後在調用查詢方法時, 傳入連線物件就可以了, 像這樣:

  User user = qr.query(conn, sql, new BeanHandler<User>(User.class));

 

2. 採用xml設定檔的方式, 程式會自動尋找設定檔
  xml的檔案名稱固定為c3p0-config.xml
  檔案在classpath路徑下,即src下, 就是類的載入路徑
  裡面的基本配置如下

<?xml version="1.0" encoding="UTF-8"?><c3p0-config>    <default-config>        <property name="driverClass">com.mysql.jdbc.Driver</property>        <property name="jdbcUrl">jdbc:mysql://localhost:3306/資料庫名</property>        <property name="user">root</property>        <property name="password">asd</property>    </default-config>    <named-config name="mysql">        <property name="driverClass">com.mysql.jdbc.Driver</property>        <property name="jdbcUrl">jdbc:mysql://localhost:3306/資料庫名</property>        <property name="user">root</property>        <property name="password">asd</property>    </named-config>    <named-config name="oracle">        ……    </named-config></c3p0-config>

如果只有<default-config>則這樣初始化資料來源:
 ComboPooledDataSource dataSource = new ComboPooledDataSource(); 
如果初始化指定名稱的資料來源如mysql, 則這樣:
 ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql"); 

 

3. 採用.porperties屬性檔案的方式
  固定檔案名稱:c3p0.properties
  檔案在classpath路徑下,即src下, 就是類的載入路徑

裡面的配置如下

c3p0.driverClass=com.mysql.jdbc.Driverc3p0.jdbcUrl=jdbc:mysql://localhost:3306/資料庫名c3p0.user=rootc3p0.password=asd

初始化資料來源:

 ComboPooledDataSource dataSource = new ComboPooledDataSource(); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.