当前位置:编程学习 > JAVA >>

用C3P0完成数据库的连接

1.封装的javabean
package com.csdn.hbsi.domain;


public class User {
private int id;
private String name;
private double price;
private String author;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}

}
2.package com.csdn.hbsi.demo;

import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.junit.Test;

import com.csdn.hbsi.domain.User;
import com.csdn.hbsi.utils.DBManager;

public class demo_crud {

@Test
public void insert() throws SQLException {
QueryRunner runner = new QueryRunner(DBManager.getDataSource());
String sql = "insert into book(id,name,price,author,description) values(?,?,?,?,?)";
Object params[] = { 5, "cc", "66", "cccc", "dd" };
runner.update(sql, params);
}
@Test
public void update() throws SQLException {
QueryRunner runner = new QueryRunner(DBManager.getDataSource());
String sql = "update book set name=? where id=?";
Object params[] = { "eeee", 3 };
runner.update(sql, params);
}

@Test
public void delete() throws SQLException {
QueryRunner runner = new QueryRunner(DBManager.getDataSource());
String sql = "delete from book where id=?";
Object params[] = { 3 };
runner.update(sql, params);
}

@SuppressWarnings("deprecation")
@Test
public void find() throws SQLException {
QueryRunner runner = new QueryRunner(DBManager.getDataSource());
String sql="select * from book where id=?";
User user=(User) runner.query(sql, 1, new BeanHandler(User.class));
System.out.println(user);
}

@Test
public void findall() throws SQLException {
QueryRunner runner = new QueryRunner(DBManager.getDataSource());
String sql="select * from book";
List list=(List) runner.query(sql, new BeanListHandler(User.class));
System.out.println(list.size());
}


}
3.配置文件

com.mysql.jdbc.Driverjdbc:mysql://localhost:3306/testroot123510530com.mysql.jdbc.Driverjdbc:mysql://localhost:3306/testroot123510530
4.package com.csdn.hbsi.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DBManager {

private static ComboPooledDataSource ds=null;
static{
ds = new ComboPooledDataSource();
}
public static ComboPooledDataSource getDataSource(){
return ds;
}
}

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,