31.【任务案例】使用DBUtils实现增删改查

本文详细介绍了如何使用C3p0连接池进行数据库连接管理,并结合DBUtils实现对数据库的增删改查操作。通过具体代码示例,展示了数据库操作的全过程,包括创建数据库、表结构、插入数据、查询、更新和删除等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.创建数据库

/*创建chapter03数据库,然后在数据库中创建一个表user,具体语句如下*/
CREATE DATABASE chapter03;
USE chapter03;
CREATE TABLE user(
id INT(3) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(20) NOT NULL,
password VARCHAR(20) NOT NULL
);

/*向user表插入三条数据,具体语句如下*/
INSERT INTO user(name,password)  VALUES('zhangsan','123456');
INSERT INTO user(name,password)  VALUES ('lisi','123456');
INSERT INTO user(name,password)  VALUES ('wangwu','123456');

/*使用SELECT语句查询users表,SQL语句如下所示*/
SELECT * FROM user;

2.C3p0Utils连接池

在cn.lctvu.utils包下创建C3p0Utils类

public class C3p0Utils {
    private static DataSource ds;
    static {
        ds=new ComboPooledDataSource();
    }
    public static DataSource getDataSource(){
        return ds;
    }
}

c3p0-config.xml

<c3p0-config>
    <default-config>
        <property name="user">root</property>
        <property name="password">root</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">
            jdbc:mysql://localhost:3306/jdbc</property>
        <property name="checkoutTimeout">30000</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
        <property name="maxStatements">200</property>
    </default-config>
    <named-config name="itcast">
        <property name="initialPoolSize">5</property>
        <property name="maxPoolSize">15</property>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">
            jdbc:mysql://localhost:3306/jdbc</property>
        <property name="user">root</property>
        <property name="password">root</property>
    </named-config>
</c3p0-config>

3.DBUtilsDao类

在cn.lctvu.dao包下创建DBUtilsDao类,该类实现了对user表增删改查的基本操作。

3.1 findAll() 方法

//查询所有,返回List集合
public List findAll() throws SQLException {
//创建QueryRunner对象
QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
//写SQL语句
String sql = “select * from users”;
//调用方法
List list = (List)runner.query(sql,new BeanListHandler(User.class));
return list;
}

3.2 根据id查询单条记录方法findUserByid(int id)

 /**
     * 根据id查询单条记录
     * @param id
     * @return
     * @throws SQLException
     */
    public User findUserByid(int id) throws SQLException{
        QueryRunner runner=new QueryRunner(C3p0Utils.getDataSource());
        String sql="select * from users where id=?";
        Object[] a={id};
        User user=runner.query(sql, new BeanHandler<>(User.class), a);
        return user;
    }

3.3 添加用户记录方法 insert(User user)

 /**
     * 添加成功返回ture,失败返回false
     * @param user
     * @return
     * @throws SQLException
     */
    public Boolean insert(User user) throws SQLException{
        //创建QueryRunner对象
        QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
        //写SQL语句
        String sql = "insert into users (name,password) values (?,?)";
        //调用方法
        int num =runner.update(sql, new Object[]{ user.getName(),user.getPassword()} );
        if (num>0){
            return true;
        }
        return false;
    }

3.4 修改用户的方法

/**
     * 修改成功返回true,失败返回false
     * @param user
     * @return
     * @throws SQLException
     */
    public Boolean update(User user) throws SQLException{
        //创建QueryRunner对象
        QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
        //写SQL语句
        String sql = "update  user set name=?,password=? where id=?";
        //调用方法
        int num =runner.update(sql, new Object[]{
                user.getName(),
                user.getPassword(),
                user.getId()
        } );
        if (num>0){
            return true;
        }
        return false;
    }

3.5 删除用户方法

/**
     * 根据id删除对应的记录,成功返回true,失败返回false
     * @param id
     * @return
     * @throws SQLException
     */
    public Boolean delete(int id) throws SQLException{
        //创建QueryRunner对象
        QueryRunner runner = new QueryRunner(C3p0Utils.getDataSource());
        //写SQL语句
        String sql = "delete from user where id=?";
        //调用方法
        int num =runner.update(sql, new Object[]{id});
        if (num>0){
            return true;
        }
            return false;
    }

4.测试

在cn.lctvu.test包中创建DBUtilsDaoTest测试类,在该 类中分别创建增删改查的测试方法

4.1 测试增加记录的方法

public class DBUtilsDaoTest1 {
    private static DBUtilsDao dao=new DBUtilsDao();
    /**
     * 测试增加记录的方法
     * @throws SQLException
     */
    public static void testInsert() throws SQLException {
        User user=new User();
        user.setName("zhaoliu");
        user.setPassword("666666");
        boolean b = dao.insert(user);
        System.out.println(b);
    }
    public static void main(String[] args) throws SQLException {
        testInsert();
    }

4.2测试修改记录的方法

public class DBUtilsDaoTest1 {
    private static DBUtilsDao dao=new DBUtilsDao();
    /**
     * 测试修改记录的方法
     * @throws SQLException
     */
    public static void testupdate() throws SQLException{
        User user=new User();
        user.setName("zhaoliu");
        user.setPassword("666777");
        user.setId(4);
        boolean b = dao.update(user);
        System.out.println(b);
    }
    public static void main(String[] args) throws SQLException {
        testupdate();
    }
}

4.3 测试删除功能

public class DBUtilsDaoTest1 {
    private static DBUtilsDao dao=new DBUtilsDao();
    /**
     * 测试删除功能
     * @throws SQLException
     */
    public static void testdelete() throws SQLException{
        boolean b = dao.delete(4);
        System.out.println(b);
    }
    public static void main(String[] args) throws SQLException {
        testdelete();
    }

4.4 测试查询单条记录功能

public class DBUtilsDaoTest1 {
    private static DBUtilsDao dao=new DBUtilsDao();
    /**
     * 测试查询单条记录功能
     * @throws SQLException
     */
    public static void testfind() throws SQLException{
        User user = dao.findUserByid(2);
        System.out.println(user.getId()+","+user.getName()+","  +user.getPassword());
    }
    public static void main(String[] args) throws SQLException {
        testfind();
    }
}

4.5 测试查询多条记录的功能

public class DBUtilsDaoTest1 {
    private static DBUtilsDao dao=new DBUtilsDao();
    /**
     * 测试查询多条记录的功能
     * @throws SQLException
     */
    public static void testFindAll() throws SQLException
    {
        List list=dao.findAll();
        for(int i=0;i<list.size();i++)
        {
            User user=(User)list.get(i);
            System.out.println("第"+(i+1)+"行的姓名:"+user.getName());
        }
    }
    public static void main(String[] args) throws SQLException
    {
        testFindAll();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

上进扣得

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值