package com.primeton.dsp.dataservice.utils;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.MapListHandler;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import javax.sql.DataSource;
import java.io.Closeable;
import java.io.IOException;
import java.sql.*;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* 数据库执行类。主要封装了查询,更新,批量更新等一些执行SQL的方法。
*
*
*
* Created by zhaopx.
* User: zhaopx
* Date: 2020-03-26
* Time: 10:20
*
*
*
* @author zhaopx
*/
@Slf4j
public class SQLRunner implements Closeable {
protected final DataSource ds;
public SQLRunner(Properties config) {
this(config.getProperty("jdbc.driverClassName"),
config.getProperty("jdbc.url"),
config.getProperty("jdbc.user"),
config.getProperty("jdbc.password"));
}
public SQLRunner(String driverClass,
String url,
String user,
String password) {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setMaxTotal(2);
dataSource.setMinIdle(1);
dataSource.setInitialSize(1);
dataSource.setDriverClassName(driverClass);
dataSource.setUrl(url);
dataSource.setUsername(user);
dataSource.setPassword(password);
this.ds = dataSource;
}
public SQLRunner(@NonNull DataSource ds) {
this.ds = ds;
}
public int update(String sql) throws SQLException {
if(sql == null) {
throw new SQLException("Null SQL statement");
}
Connection conn = ds.getConnection();
if(conn == null) {
throw new SQLException("Null connection");
}
Statement statement = null;
int r = 0;
try {
statement = conn.createStatement();
r = statement.executeUpdate(sql);
} finally {
close(conn, statement, null);
}
return r;
}
public int update(String sql, Object[] params) throws SQLException {
QueryRunner runner = new QueryRunner(this.ds);
return runner.update(sql, params);
}
/**
* 批量更新
* @param sql SQL 值 ? 代替
* @param params 参数数组
* @return
* @throws SQLException
*/
public int[] updateBatch(String sql, List