Java 之QueryRunner实现增删改查

一、导包

DbUtil

package utils;

import java.sql.Connection;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.apache.commons.dbutils.QueryRunner;

import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DbUtil {
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    public static DataSource getDataSource() {
        return dataSource;
    }
    
    public static Connection getConnect() {
        Connection conn = null;
        if(conn == null) {
            try {
                conn = dataSource.getConnection();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return conn;
    }
    
    public static QueryRunner queryRunner() {
        return new QueryRunner(dataSource);
    }
}

二、操作

1、增

@Override
public int AddTable(Table table) throws SQLException {
    Object params[] = { table.getName(), table.getDate_entered() };
    return DbUtil.queryRunner().update(DbUtil.getConnect(), "insert into tp_table (name, date_entered) values (?,?)",
                params);
}

2、删

@Override
public int deleteTable(int id) throws SQLException {
    return DbUtil.queryRunner().update("delete from tp_table where id=?", id);
}

3、改

public int updateTable(Table table) throws SQLException {
    return DbUtil.queryRunner().update("update tp_table set name=?, status=? where id=?", table.getName(), table.getStatus(), table.getId());
}

4、查

a、查所有

@Override
public List<Table> selectTableList(int page, int pagesize, String condition) throws SQLException {
    int offset = (page - 1) * pagesize;
    StringBuffer sb = new StringBuffer();
    sb.append("select * from tp_table ");
    if (condition != null) {
        sb.append("where " + condition + " ");
    }
    sb.append("limit " + offset + "," + pagesize);
    Object[] params = {};

    return DbUtil.queryRunner().query(sb.toString(), new BeanListHandler<Table>(Table.class), params);

}  

b、查数量

@Override
public int selectTableListCount(String condition) throws SQLException {
    Object params[] = {};
    String sql = "select count(*) as count from tp_table";
    if (condition != null) {
        sql += " where " + condition;
    }
    Long count = DbUtil.queryRunner().query(sql, new ScalarHandler<Long>(), params);
    return count.intValue();
}

c、查单个

@Override
public Table getTableById(int id) throws SQLException {
    Object params[] = {id};
    return DbUtil.queryRunner().query("select * from tp_table where id=?", new BeanHandler<Table>(Table.class), params);
}
原文地址:https://www.cnblogs.com/yang-2018/p/15097485.html