Java DataSource 访问数据库

首先给大家推荐一下我老师大神的人工智能教学网站。教学不仅零基础,通俗易懂,而且非常风趣幽默,还时不时有内涵黄段子!点这里可以跳转到网站

以前呢,我们是通过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));		}	}}

点这里可以跳转到人工智能网站

发表评论