java connectionpool mysql_java – 使用ConnectionPoolDataSource的连接

尝试阅读

this文档和

example

编辑

刚从上面链接修改了示例

delimiter $$

CREATE DATABASE `test_stackoverflow` /*!40100 DEFAULT CHARACTER SET utf8 */$$

delimiter $$

CREATE TABLE `test_table` (

`idtest_table` int(11) NOT NULL,`test_field` varchar(45) DEFAULT NULL,PRIMARY KEY (`idtest_table`)

) ENGINE=InnoDB DEFAULT CHARSET=utf8$$

INSERT INTO `test_stackoverflow`.`test_table` (`idtest_table`,`test_field`) VALUES (1,'test1');

INSERT INTO `test_stackoverflow`.`test_table` (`idtest_table`,`test_field`) VALUES (2,'test2');

>创建java项目,添加到类路径,myscl连接器,池和dbcp(你只需下载所有这些jar)

添加下一个课程

import org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS;

import org.apache.commons.dbcp.datasources.SharedPoolDataSource;

import javax.sql.DataSource;

import java.sql.Connection;

import java.sql.sqlException;

/**

* @author Sergii.Zagriichuk

*/

public class Pool {

private static DataSource ds;

static {

DriverAdapterCPDS cpds = new DriverAdapterCPDS();

try {

cpds.setDriver("com.MysqL.jdbc.Driver");

} catch (ClassNotFoundException e) {

e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.

}

cpds.setUrl("jdbc:MysqL://localhost:3306/test_stackoverflow");

cpds.setUser("root");

cpds.setPassword("root");

SharedPoolDataSource tds = new SharedPoolDataSource();

tds.setConnectionPoolDataSource(cpds);

tds.setMaxActive(10);

tds.setMaxWait(50);

ds = tds;

}

public static Connection getConnection() throws sqlException {

return ds.getConnection();

}

}

用户名和密码应更改为您的数据库用户/密码

import java.sql.Connection;

import java.sql.ResultSet;

import java.sql.sqlException;

import java.sql.Statement;

public class MainClass {

public static void main(String[] args) {

Connection connection = null;

Statement statement = null;

ResultSet resultSet = null;

try {

connection = Pool.getConnection();

// Do work with connection

statement = connection.createStatement();

String selectEmployeessql = "select * from test_table";

resultSet = statement.executeQuery(selectEmployeessql);

while (resultSet.next()) {

printTestTable(resultSet);

}

} catch (Exception e) {

e.printStackTrace();

} finally {

if (resultSet != null) {

try {

resultSet.close();

} catch (sqlException e) {

} // nothing we can do

}

if (statement != null) {

try {

statement.close();

} catch (sqlException e) {

} // nothing we can do

}

if (connection != null) {

try {

connection.close();

} catch (sqlException e) {

} // nothing we can do

}

}

}

private static void printTestTable(ResultSet resultSet) throws sqlException {

System.out.print(resultSet.getInt("idtest_table")+",");

System.out.print(resultSet.getString("test_field"));

}

}

只需运行main方法,您将看到打印测试值到控制台!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值