DBUtils和C3P0介绍
DBUtils是java编程中的数据库操作使用工具,小巧简单实用。对于数据库表的操作,可以把结果转换成List,Array,Set等Java集合。 是 Apache 组织提供的一个开源 JDBC工具类库,它是对JDBC的简单封装,学习成本极低,并且使用dbutils能极大简化jdbc编码的工作量,同时也不会影响程序的性能。
DBUtils有几个重要的类,简要介绍
1.QueryRunner---用来做查询,更新操作。 JavaBean
2.BeanHandle---将ResultSet中的一行数据转换成类对象。(平常的登录操作可以用这个,可以返回一个类对象)
3.BeanListHandle---将ResultSet中的所有数据转换成list,list存放的是类对象(比如说返回一张表的全部内容,就可以用这个,比较方便)
C3P0是一个开源的JDBC连接池
使用jdbc进行数据库操作的时候,每次都要获取连接对象,操作完毕后都要关闭连接对象,这是一种耗费资源的操作。
数据库连接池的基本思想就是为数据库连接建立一个“缓冲池”。预先在缓冲池中放入一定数量的连接,当需要建立数据库连接时,只需从“缓冲池”中取出一个,使用完毕之后再放回去。我们可以通过设定连接池最大连接数来防止系统无尽的与数据库连接。
DBUtils结合C3p0会使数据库连接操作代码变得更加简单。
操作流程
1、使用mysql数据库建表
mysql> create table students(
id int(5) primary key auto_increment,//主键自增
name varchar(10) not null,//姓名不能为空
age int(3),
email varchar(10),
sex int(2),
address varchar(20),
birth date);
插入数据,如图所示:
2、代码编写
第一步:导入jar包(可自行下载)
> c3p0-0.9.1.2.jar //c3p0连接池的jar包
commons-dbutils-1.4.jar // dbutils的jar包
commons-pool-1.5.6.jar //
mysql-connector-java-5.1.6-bin.jar//连接mysql数据库的jar包
第二步:编写c3p0配置文件信息+读取配置信息
在src下面新建c3p0-config.xml,名字和位置一定不能写错
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<!-- 配置MySql数据库 -->
<default-config>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/bxk</property>
<property name="user">root</property>
<property name="password">syx</property>
<!-- 自增量 -->
<property name="acquireIncrement">5</property>
<!-- 初始化链接个数 -->
<property name="initialPoolSize">10</property>
<!-- 最少连接数 -->
<property name="minPoolSize">5</property>
<!-- 最大连接数 -->
<property name="maxPoolSize">20</property>
</default-config>
<!-- 配置Oracle数据库 -->
<named-config name="oracle">
<property name="driverClass">oracle.jdbc.driver.OracleDriver</property>
<property name="jdbcUrl">jdbc:oracle:thin:@localhost:1521:数据库名</property>
<property name="user">root</property>
<property name="password">root</property>
<property name="acquireIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
</c3p0-config>
第三步:读取配置信息的工具类
package com.bxk.util;
import javax.sql.DataSource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class ReadDataSource {
private static DataSource ds;
//默认的就去读取xml中的default配置信息
static{
ds=new ComboPooledDataSource();
}
public static DataSource getDataSource(){
return ds;
}
}
第四步:编写实体类entity
//映射: java实体类--》数据库中的表
// 属性-----》 字段
// 对象-----》记录
//注意:实体类属性名和数据库表中字段名要保持一致
public class Student {
private int id;
private String name;
private int age;
private String email;
private String sex;
private String address;
private Date birth;
//有参构造器、无参构造器、set和get方法、toString方法自行添加
第五步:编写dao层代码
public interface StudentDao {
//增加
public void addStudent(Student stu) throws SQLException;
//删除
public void delStudent(int no);
//修改
public void updateStudent(Student stu);
//查询 ->集合中存储学生信息
public List<Student> queryAllStus() throws SQLException;
//根据no查询
public Student queryStuByNo(int no) throws SQLException;
//查询总数
public int getCount() throws Exception;
//登陆用户名和密码验证
public boolean checkNameAndPwd(String name,String pwd);
//批量删除
public void delBatch(String ids) throws SQLException ;
//模糊查询
public void queryByNameLike(String name);
}
第六步:编写dao层实现类
package com.bxk.dao;
import java.sql.Date;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import com.bxk.entity.Student;
import com.bxk.util.ReadDataSource;
public class StudentDaoImpl implements StudentDao {
//读取属性文件 xml
DataSource ds=ReadDataSource.getDataSource();
@Override
public void addStudent(Student stu) throws SQLException {
QueryRunner qr=new QueryRunner(ds);
String sql="insert into students(name,age,email,sex,address,birth) values(?,?,?,?,?,?)";
Object [] params={stu.getName(),stu.getAge(),stu.getEmail(),stu.getSex(),stu.getAddress(),new Date(stu.getBirth().getTime())};
qr.update(sql,params);
}
@Override
public void delStudent(int id) throws SQLException {
QueryRunner qr = new QueryRunner(ds);
String sql = "delete from students where id=?";
qr.update(sql,id);
}
@Override
public void updateStudent(Student stu) throws SQLException {
QueryRunner qr=new QueryRunner(ds);
String sql="update students set id=?,name=?,age=?,email=?,sex=?,address=?,birth=? where id=?";
Object [] params={stu.getId(),stu.getName(),stu.getAge(),stu.getEmail(),stu.getSex(),stu.getAddress(),new Date(stu.getBirth().getTime()),stu.getId()};
qr.update(sql,params);
}
@Override
public List<Student> queryAllStus() throws SQLException {
QueryRunner qr=new QueryRunner(ds);
String sql="select * from students";
return qr.query(sql,new BeanListHandler<Student>(Student.class));
}
@Override
public Student queryStuByNo(int no) throws SQLException {
QueryRunner qr=new QueryRunner(ds);
String sql="select * from students where id=?";
return qr.query(sql,new BeanHandler<Student>(Student.class),no);
}
@Override
public int getCount() throws Exception {
QueryRunner qr=new QueryRunner(ds);
String sql="select count(*) from students";
long count = (Long) qr.query(sql, new ScalarHandler());
return (int)count;
}
@Override
public boolean checkNameAndPwd(String name, int pwd) throws SQLException {
QueryRunner qr=new QueryRunner(ds);
//把年龄当作密码使用
String sql="select * from students where name=? and age=?";
Student stu= qr.query(sql,new BeanHandler<Student>(Student.class),name,pwd);
if(stu!=null){
return true;
}else{
return false;
}
}
@Override
public void delBatch(String ids) throws SQLException {
QueryRunner qr = new QueryRunner(ds);
String sql = "delete from students where id in ("+ids+")";
System.out.println(sql);
qr.update(sql);
}
@Override
public List<Student> queryByNameLike(String name) throws SQLException {
QueryRunner qr=new QueryRunner(ds);
String sql="select * from students where name like '%"+name+"%'";
return qr.query(sql,new BeanListHandler<Student>(Student.class));
}
}
第七步:测试实现方法的正确性
public static void main(String[] args) throws Exception {
StudentDao stu=new StudentDaoImpl();
stu.delStudent(8);
// stu.addStudent(new Student("王五", 23, "3@163.com", 0, "北京", new Date()));
// System.out.println(stu.getCount());
// stu.updateStudent(new Student(3,"王五55", 23, "3@163.com", 0, "北京", new Date()));
//System.out.println(stu.queryStuByNo(1));
// Student s=new Student();
// s.setName("moni");
// s.setNo(11);
// s.setAge(90);
// //stu.addStudent(s);
// //System.out.println(stu.queryStuByNo(11));
ArrayList ss=(ArrayList) stu.queryByNameLike("a");
for (Object object : ss) {
System.out.println(object);
}
//System.out.println(stu.checkNameAndPwd("aa", 12));
//stu.delBatch("7,9,10");
}
此博客适用于初学者,按照步骤慢慢来。