commons-dbutils commons-dbutils 1.6
import java.sql.*;
/**
* JDBC工具类
* 包含数据库连接及关闭数据库资源
*/
public class JDBCUtils3 {
private static String driver = "com.mysql.cj.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&serverTimezone=GMT%2B8&characterEncoding=UTF-8&useSSL=false&rewriteBatchedStatements=true&allowMultiQueries=true";
private static String username = "root";
private static String password = "root";
static {
try {
// 加载数据库驱动
Class.forName(driver);
} catch (Exception e) {
throw new ExceptionInInitializerError(e);
}
}
static Connection connection = null;
/**
* @Method: getConnection
* @Description: 获取数据库连接对象
* @Anthor:孤傲苍狼
*
* @return Connection数据库连接对象
* @throws SQLException
*/
public static Connection getConnection(){
try {
if(connection == null){
connection = DriverManager.getConnection(url, username, password);
}
return connection;
}catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
/**
* @Method: release
* @Description: 释放资源, 要释放的资源包括Connection数据库连接对象,负责执行SQL命令的Statement对象,
* 存储查询结果的ResultSet对象
*
* @param conn
* @param st
* @param rs
*/
public static void release(Connection conn, Statement st, ResultSet rs) {
if (rs != null) {
try {
// 关闭存储查询结果的ResultSet对象
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
rs = null;
}
if (st != null) {
try {
// 关闭负责执行SQL命令的Statement对象
st.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
// 关闭Connection数据库连接对象
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
实现了创建表、删除表、增加数据、查询一条数据、分页查询数据
package com.itl.iap.energy.provider.dbhelp;
import com.itl.iap.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Slf4j
@Component
public class DBHelper {
@Autowired
private JDBCUtils jdbcUtils;
private static QueryRunner qr = new QueryRunner();
/**
* 创建表
* @param tableName
*/
public void createTable(String tableName) {
try {
PreparedStatement ps=jdbcUtils.getConnection().prepareStatement(String.format(createSQL,tableName,tableName));
ps.executeUpdate();//执行sql语句
log.info("数据表:{}创建成功",tableName);
}catch (Exception e){
log.error("数据表:{}创建失败:{}",tableName,e);
}
}
/**
* 创建表
* @param tableName
*/
public void deleteTable(String tableName) {
try {
PreparedStatement ps=jdbcUtils.getConnection().prepareStatement("DROP TABLE "+tableName);
ps.executeUpdate();//执行sql语句
log.info("数据表:{}删除成功",tableName);
}catch (Exception e){
log.error("数据表:{}删除失败:{}",tableName,e);
}
}
/**
* 查询一条数据
* @param tableName
* @param p
*/
public void addOne(String tableName,Parameter p){
try {
String sql = String.format(insertSQL, tableName);
int insertCount = qr.update(jdbcUtils.getConnection(), sql,p.getParameterNo(),p.getParameterName(),p.getParameterUnit(),
p.getParameterValue(),p.getCollectionTime(),p.getOperator(),p.getOperation(),p.getStation(),
p.getShopOrder(), p.getCreated_by(),p.getCreationTime());
log.info("表:{},增加了一条记录",tableName,insertCount);
}catch (Exception e){
log.error("表:{},增加记录失败:{}",tableName,e);
}
}
/**
* 根据id查询一条数据
* */
public Parameter getById(String tableName,int id) {
try {
String sql = "SELECT * FROM "+ tableName +" WHERE ID="+id;
// 返回一个
Parameter parameter = qr.query(jdbcUtils.getConnection(), sql,new BeanHandler(Parameter.class));
log.info("getById:{}",parameter.toString());
return parameter;
}catch (Exception e){
log.error("查询失败:id:{},{}",id,e);
}
return null;
}
/**
* 分页查询用
* */
public Map page(String tableName, int pageIndex, int pageSize, Parameter parameter) {
Map resMap = new HashMap<>();
try {
if(pageIndex == 0){
pageIndex =1;
}
int start = (pageIndex * pageSize);
String sql = String.format(listSql,tableName,start,pageSize);
String sqlCountTotal = String.format(listSqlTotal,tableName);
String sql2 = "";
if(StringUtils.isNotBlank(parameter.getParameterNo())){
sql2=" and parameter_no ="+parameter.getParameterNo();
}
if(StringUtils.isNotBlank(parameter.getParameterName())){
sql2=" and parameter_name like '%"+parameter.getParameterName()+"%'";
}
if(StringUtils.isNotBlank(parameter.getStartTime())){
sql2=" and collection_time >= "+parameter.getStartTime();
}
if(StringUtils.isNotBlank(parameter.getEndTime())){
sql2=" and collection_time <= "+parameter.getEndTime();
}
sql = sql.replace("replace",sql2);
sqlCountTotal = sqlCountTotal.replace("replace",sql2);
// 返回对象数组
Connection connection = jdbcUtils.getConnection();
List list = qr.query(connection, sql, new BeanListHandler(Parameter.class));
long countTotal = qr.query(connection,sqlCountTotal,new ScalarHandler());
resMap.put("list",list);
long pageTotal = countTotal /pageSize;
if(countTotal % pageSize !=0){
pageTotal+=1;
}
resMap.put("total",countTotal);
resMap.put("pageTotal",pageTotal);
resMap.put("pageSize",pageSize);
resMap.put("currentIndex",pageIndex);
return resMap;
}catch (Exception e){
log.error("查询失败:{}",e);
}
return null;
}
private static String createSQL="CREATE TABLE %s("+
"id bigint(32) NOT NULL AUTO_INCREMENT COMMENT 'id',"+
"parameter_no varchar(30) DEFAULT NULL COMMENT '参数编号',"+
"parameter_name varchar(30) DEFAULT NULL COMMENT '参数名称',"+
"parameter_unit varchar(10) DEFAULT NULL COMMENT '单位',"+
"parameter_value varchar(30) DEFAULT NULL COMMENT '参数值',"+
"collection_time datetime DEFAULT NULL COMMENT '采集时间',"+
"operator varchar(30) DEFAULT NULL COMMENT '作业者',"+
"operation varchar(30) DEFAULT NULL COMMENT '工序',"+
"station varchar(30) DEFAULT NULL COMMENT '工位',"+
"shop_order varchar(30) DEFAULT NULL COMMENT '工单',"+
"created_by varchar(10) DEFAULT NULL COMMENT '创建者',"+
"creation_time datetime DEFAULT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',"+
"PRIMARY KEY (id)"+
") ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='采集数据%s';";
private static String insertSQL="INSERT INTO `%s` (`parameter_no`, `parameter_name`, `parameter_unit`, `parameter_value`, `collection_time`, `operator`, `operation`, `station`, `shop_order`, `created_by`, `creation_time`)" +
" VALUES (?,?,?, ?,?,?,?,?,?,?,?);";
private static String listSql = "SELECT * FROM %s WHERE 1=1 replace LIMIT %d,%d";
private static String listSqlTotal = "SELECT COUNT(*) FROM %s WHERE 1=1 replace ";
public static void main(String[] args) throws SQLException {
//createTable("test1");
//deleteTable("test1");
/*for (int i = 0;i<23;i++){
Parameter p = new Parameter();
p.setCollectionTime(LocalDateTime.now());
p.setCreated_by("test");
p.setCreationTime(LocalDateTime.now());
p.setOperator("hlw");
p.setOperation("operation");
p.setParameterName("原料批次");
p.setParameterNo("SC202211160007");
p.setParameterUnit("次");
p.setParameterValue("44555");
p.setStation("9");
p.setShopOrder("JH20221010003");
addOne("test1",p);
}*/
//getById("test1",2);
/* Parameter q = new Parameter();
q.setParameterName("原料批");
q.setStartTime("'2022-11-29 13:33:37'");
q.setEndTime("'2022-11-29 14:33:37'");
Map test1 = page("test1", 0, 2, q);
System.out.println(test1);*/
}
}