DBUtils对数据库操作用例

package org.fjzzy.JDBC;

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

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

import static org.junit.jupiter.api.Assertions.*;

class JDBCUtilsTest {

    @Test
    /**
     * 添加
     */
    void Add() {
        QueryRunner qr =  new QueryRunner(JDBCUtils.getDataSource());
        String sql = "insert into users values(?,?)";
        Object[] params = {"ddfU","wwffaaw"};
        try {
            int rows = qr.update(sql,params);
            if (rows>0)
                System.out.println("添加成功");
            else
                System.out.println("添加失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }

    /**
     * 修改
     */
    @Test
    void Update(){
        QueryRunner qr =  new QueryRunner(JDBCUtils.getDataSource());
        String sql = "update users set password=? where username=?";
        try {
            Object[] params = {"ssss","ddd"};
            int rows = qr.update(sql,params);
            if (rows>0)
                System.out.println("修改成功");
            else
                System.out.println("修改失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除
     */
    @Test
    void Delete(){
        QueryRunner qr =  new QueryRunner(JDBCUtils.getDataSource());
        String sql = "delete from users where username=?";
        try {
            Object[] params = {"ddd"};
            int rows = qr.update(sql,params);
            if (rows>0)
                System.out.println("删除成功");
            else
                System.out.println("删除失败");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    /**
     * 查询单条内容
     */
    @Test
    void Query(){
        QueryRunner qr =  new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from users where username=?";
        Object[] params = {"YOU"};
        try {
            User user = qr.query(sql,new BeanHandler<User>(User.class),params);
            System.out.println(user.getUsername()+"----------"+user.getPassword());

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 查询多条内容
     */
    @Test
    void Querylist(){
        QueryRunner qr =  new QueryRunner(JDBCUtils.getDataSource());
        String sql = "select * from users";
        try {
            List<User> users = qr.query(sql,new BeanListHandler<User>(User.class));
            for (User user:users) {
                System.out.println(user.getUsername()+"----------"+user.getPassword());
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

}

分享:

发表评论

电子邮件地址不会被公开。 必填项已用*标注

😉😐😡😈🙂😯🙁🙄😛😳😮:mrgreen:😆💡😀👿😥😎😕