c3p0连接池Demo
/**
* c3p0连接池demo
* 依赖包:
* c3p0-0.9.5.2.jar
* mcchange-commons-java.jar
*/
// 创建连接池
ComboPooledDataSource combo = new ComboPooledDataSource();
// 从连接池获取连接对象
Connection conn = combo.getConnection();
PreparedStatement stmt = conn.prepareStatement("select * from emp");
druid连接池Demo
/**
* 依赖包:druid.jar
*/
// 类加载器获取配置文件输入流对象
InputStream is= DruidTest.class.getClassLoader().getResourceAsStream("druid.properties");
Properties ps = new Properties();
ps.load(is);
// 创建连接池对象
DataSource ds = DruidDataSourceFactory.createDataSource(ps);
// 从连接池获取连接对象
Connection conn = ds.getConnection();
PreparedStatement stmt = conn.prepareStatement("select * from emp");
c3p0加dbUtils
// 依赖包:commons.dbutils.jar
public class DbUtils {
static ComboPooledDataSource pool = new ComboPooledDataSource();
static QueryRunner qr = new QueryRunner(pool);
@Test
public void add() throws SQLException {
String sql = "insert into `job` values (null,'清洁工','扫地')";
qr.update(sql);
}
@Test
public void delete() throws SQLException {
String sql = "delete from job where `jname`=?";
qr.update(sql,"清洁工");
}
// 得到查询结果的首个对象的数组形式
@Test
public void query1() throws SQLException {
String sql = "select * from job";
Object[] obj = qr.query(sql, new ArrayHandler());
System.out.println(Arrays.toString(obj)); // [1, 董事长, 管理整个公司,接单]
}
// 得到查询结果的所有对象的数组形式
@Test
public void query2() throws SQLException {
String sql = "select * from job";
List<Object[]> obj = qr.query(sql, new ArrayListHandler());
for (Object[] objects : obj) {
System.out.println(Arrays.toString(objects));
}
/*
* [1, 董事长, 管理整个公司,接单]
* [2, 经理, 管理部门员工]
* [3, 销售员, 向客人推销产品]
* [4, 文员, 使用办公软件]
* [5,总经理, 打扫卫生]
*/
}
// 得到查询的首个对象的Job对象形式
@Test
public void query3() throws SQLException {
String sql = "select * from job";
Job j = qr.query(sql, new BeanHandler<>(Job.class));
System.out.println(j);
}
// 得到查询结果集的所有对象的Job对象形式
@Test
public void query4() throws SQLException {
String sql = "select * from job";
List<Job> j = qr.query(sql, new BeanListHandler<>(Job.class));
System.out.println(j);
}
// 得到单个查询结果
@Test
public void query5() throws SQLException {
String sql = "select `jname` from job where `id`=1";
Object obj = qr.query(sql, new ScalarHandler());
System.out.println(obj);
}
}