以前呢,我們是通過DriverManager這個類來的得到Connection對象的。
現在我們通過DataSource來得到Connection,
其餘的都是一樣的東西,
先上DataSource得到Connection的代碼。
在這之前,先將db.properties設定檔的內容考進來
jdbc.datasource=com.mchange.v2.c3p0.ComboPooledDataSourcejdbc.driverClass=com.mysql.jdbc.Driverjdbc.jdbcUrl=jdbc:mysql://localhost:3306/testjdbc.user=rootjdbc.password=jdbc.maxPoolSize=100jdbc.minPoolSize=2jdbc.initialPoolSize=2jdbc.acquireIncrement=2jdbc.maxStatements=1000jdbc.maxIdleTime=300jdbc.checkoutTimeout=5000
獲得的Connection的講解全在代碼注釋上,
package org.test;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Properties;import javax.sql.DataSource;import org.apache.commons.beanutils.BeanUtils;public class JdbcDataSourceTest{private static DataSource dataSource;private static Connection connection;private static PreparedStatement ps;private static ResultSet rs;public static void main(String[] args) throws Exception{Properties properties = new Properties();//從指定的設定檔載入資料到properties中properties.load(JdbcDataSourceTest.class.getClassLoader().getResourceAsStream("db.properties"));/** * properties其中一條記錄是這樣的 * jdbc.datasource=com.mchange.v2.c3p0.ComboPooledDataSource * 將前面的jdbc.去掉在重新裝入一個Properties中 */Properties dbProperties = new Properties();for (Object key : properties.keySet()){String temp = (String) key;if (temp.startsWith("jdbc.")){String name = temp.substring(5);dbProperties.put(name, properties.getProperty(temp));}}//列出dbProperties中的所有屬性dbProperties.list(System.out);System.out.println("==============================================");//從廠商提供的DataSource實現中載入其對象dataSource = (DataSource) Class.forName(properties.getProperty("jdbc.datasource")).newInstance();//將dbProperties屬性中的內容加入到dataSource對象中BeanUtils.populate(dataSource, dbProperties);connection = dataSource.getConnection();ps = connection.prepareStatement("select * from test");rs = ps.executeQuery();while (rs.next()){System.out.println(rs.getString(1));}}}
再來就是上以前通過DriverManager來得到Connection的代碼
package org.test;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;public class JdbcTest{private static Connection connection ;private static PreparedStatement ps ;private static ResultSet rs ;static {try{Class.forName("com.mysql.jdbc.Driver");}catch (ClassNotFoundException e){e.printStackTrace();}}public static void main(String[] args) throws Exception{connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","");ps = connection.prepareStatement("select * from test");rs = ps.executeQuery();while (rs.next()){System.out.println(rs.getString(1));}}}