Java DataSource 訪問資料庫
阿新 • • 發佈:2019-02-10
以前呢,我們是通過DriverManager這個類來的得到Connection物件的。
現在我們通過DataSource來得到Connection,
其餘的都是一樣的東西,
先上DataSource得到Connection的程式碼。
在這之前,先將db.properties配置檔案的內容考進來
jdbc.datasource=com.mchange.v2.c3p0.ComboPooledDataSource jdbc.driverClass=com.mysql.jdbc.Driver jdbc.jdbcUrl=jdbc:mysql://localhost:3306/test jdbc.user=root jdbc.password= jdbc.maxPoolSize=100 jdbc.minPoolSize=2 jdbc.initialPoolSize=2 jdbc.acquireIncrement=2 jdbc.maxStatements=1000 jdbc.maxIdleTime=300 jdbc.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)); } } }