优化JDBC开发的流程,使开发者只注重业务需求,而不要关注繁琐的jdbc开发步骤。
步骤:
- 先从官网去下载DBUtils的jar包 commons-dbutils-1.6.jar 放到classpath类路径下,也就是 lib文件夹下面,依赖于数据源
- 还要下载数据库连接池jar包 c3p0 / druid 数据库驱动jar包、commons-logging.jar包
- 搭建数据源工具类 DruidDBUtil 可以获取数据源
- 从数据源中获取连接 ----> DBUtils来直接操作sql
- api常用方法:
- update(): DML语句 增删改操作 insert delete update
- query(): DQL语句 查询操作 select
- 具体操作:
- 第一步:先构建QueryRunner类对象 依赖于数据源
- 第二步:根据操作的类型选择update、query
- update (sql,Object… parameters) -----> 增删改
- query(sql,Object … pararmeters, ResultSetHandle接口实现类<对应的字节码对象类型>)
- BeanHandle -----> 装配一个Bean对象
- BeanListHandle -----> 装配多个Bean对象
- MapListHandle -----> 装配多个Bean对象,每一个Bean对象被装配到Map集合中
- 注意:ScalaHandle类型 ----> 默认返回值是long类型的
具体操作:
数据库映射实体类
public class Account implements Serializable{
private static final long serialVersionUID = 1L;
private int id;
private String username;
private double balance;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public Account() {
super();
// TODO Auto-generated constructor stub
}
public Account(int id, String username, double balance) {
super();
this.id = id;
this.username = username;
this.balance = balance;
}
@Override
public String toString() {
return "Account [id=" + id + ", username=" + username + ", balance=" + balance + "]";
}
}
德鲁伊Druid的配置文件信息:
# 键值对格式的 键和值用=连接
# 连接数据库的四大组件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///java31?characterEncoding=utf8
username=root
password=admin
#初始化池子的连接数量
initialSize=10
# 最大池子连接数量
maxActive=50
#最长等待时间
maxWait=3000
工具类数据库池
public class DruidDBUtil {
private static DataSource pool;
static {
// 使用Properties
Properties properties = new Properties();
// 使用properties集合读取配置文件
InputStream is = DruidDBUtil.class.getClassLoader().getResourceAsStream("db.properties");
try {
// 读取配置文件信息
properties.load(is);
// 创建连接池
pool = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
System.out.println("创建数据源失败哦....");
e.printStackTrace();
}
}
// 对外提供获取连接的方法
public static Connection getConnection() throws SQLException {
return pool.getConnection();
}
// 对外提供数据源的方法
public static DataSource getDataSource() {
return pool;
}
// 释放资源
public static void closeAll(ResultSet set, PreparedStatement ps, Connection con) {
if (set != null) {
try {
set.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
测试类
public class DBUtilsDemo01 {
// 构建QueryRunner类对象
private static QueryRunner runner = new QueryRunner(DruidDBUtil.getDataSource());
public static void main(String[] args) throws SQLException {
// 添加一条数据
/**
* insertData();
*/
// 修改一条数据
/**
* updateDate();
*/
// 删除一条数据
/**
* deleteData();
*/
// 查询一条数据
/**
* System.out.println(QueryOne());
*/
/**
* System.out.println(Querytow());
*/
// 查询总信息值
/**
* System.out.println(queryAll());
*/
/**
* System.out.println(queryAll02());
*/
// 查询总记录数
/**
* System.out.println(queryTotalNum());
*/
}
public static void insertData() throws SQLException {
// 往account表中添加一条数据
String sql = "insert into account values(null,?,?)";
int count = runner.update(sql, "小花", 4000);
if (count > 0) {
System.out.println("数据添加成功");
} else {
System.out.println("数据添加失败");
}
}
// 修改一条数据
public static void updateDate() throws SQLException {
int count = runner.update("update account set balance = ? where username = ?", 10000, "小花");
if (count > 0) {
System.out.println("数据修改成功");
} else {
System.out.println("数据修改失败");
}
}
// 删除一条数据
public static void deleteData() throws SQLException {
int count = runner.update("delete from account where username = ?", "小花");
if (count > 0) {
System.out.println("数据删除成功");
} else {
System.out.println("数据删除失败");
}
}
// 查询一条数据
public static Account QueryOne() throws SQLException {
// BeanHandle对ResultSetHandle做了实现
return runner.query("select * from account where id = ?", new BeanHandler<>(Account.class), 2);
}
public static Account Querytow() throws SQLException {
return runner.query("select * from account where username = ?", new BeanHandler<>(Account.class), "张三");
}
// 查询总信息值
public static List<Account> queryAll() throws SQLException {
// BeanListHandle (装多条记录) 对ResultSetHandle做了实现
return runner.query("select * from account", new BeanListHandler<>(Account.class));
}
public static List<Map<String, Object>> queryAll02() throws SQLException {
// MapListHandler (装多条记录) 对ResultSetHandle做了实现
return runner.query("select * from account", new MapListHandler());
}
// 查询总记录数
public static long queryTotalNum() throws SQLException {
// ScalarHandle 对ResultSetHandle做了实现
return runner.query("select count(*) from account where id>?", new ScalarHandler<>(), 1);
}
}