德鲁伊连接池实现mysql的简单查询

博客介绍了从Maven仓库下载Druid连接池Jar的地址,还说明了在工程中通过配置文件(db.properties)完成德鲁伊配置的方法,并提及程序实现的核心代码,涉及数据库连接池相关内容。

Jar的下载地址,从maven仓库下载
http://central.maven.org/maven2/com/alibaba/druid/

在工程中使用配置文件完成德鲁伊配置(db.properties)

配置文件:

driverClassName=com.mysql.jdbc.Driver
username=root(您的mysql用户名)
password=******(您的数据库密码)
url=jdbc:mysql://localhost:3306/rolesys
initialSiz=5
maxActive=15

Tips:所有的属性名称,参考上面的properties文件。
程序实现核心代码:

public class DruidTest {
	@Test
	public void testDruidconf() throws Exception {
		Properties properties = new Properties();
		properties.load(DruidTest.class.getResourceAsStream("/db.properties"));
		DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
		Connection coon = dataSource.getConnection();
		// 下面的“tright”为对应的数据库中的表名
		PreparedStatement pst = coon.prepareStatement("select * from tright");
		ResultSet rs = pst.executeQuery();
		while (rs.next()) {
			System.out.println(rs.getInt("id") + ":" + rs.getString("rightName"));
		}
	}

    @Test
	public void testDruid() {
		DruidDataSource datasource = new DruidDataSource();
		datasource.setUrl("jdbc:mysql://localhost:3306/rolesys");
		datasource.setDriverClassName("com.mysql.jdbc.Driver");
		datasource.setUsername("root");
		datasource.setPassword("******");
		try {
			DruidPooledConnection conn = datasource.getConnection();
			PreparedStatement pst = conn.prepareStatement("select * from tright");
			ResultSet rs = pst.executeQuery();
			while (rs.next()) {
				System.out.println(rs.getInt("id") + ":" + rs.getString("rightName") + "&" + rs.getString("rightDesc"));
             }
           } 
catch (SQLException e) {

e.printStackTrace();
       }
     }
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值