1、DBCP工具类的实现:
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
public class DBCPUtils {
private static BasicDataSource ds;
private static String dbName = "logandreg";
private static String driverClassName = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost/" + dbName; //+一个具体的数据库名称
private static String userName = "root";
private static String password = "*****";
static {
ds = new BasicDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(url);
ds.setUsername(userName);
ds.setPassword(password);
}
//注意返回到通用接口上
public static DataSource getConnection() {
return ds;
}
}
2、核心操作:
//获取DButils的QueryRunner
QueryRunner qr = new QueryRunner(DBCPUtils.getConnection());
//一个接收数据库中一行数据的JavaBean,或者一个List<User> users
User user = null;
//sql语句
String sql = "select * from users where username = ? and psword = ?";
//执行查询所需要的参数
Object[] params = {username,psword};
/*
Object BeanHandler<Object>(Object.class)
List<Object> BeanListHandler<>(Object.class)
*/
try { //操作数据库
user = qr.query(sql,new BeanHandler<User>(User.class), params);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}