public class DateBaseUtil {
private static Logger logger = Logger.getLogger(DateBaseUtil .class);
private static final String driver = "com.mysql.cj.jdbc.Driver";
private static final String TABLE_NAME_TASK = "test";
static {
try {
Class.forName(driver);
logger.info("加载驱动成功");
} catch (ClassNotFoundException e) {
logger.error(e.getMessage(),e);
}
}
protected static Connection getConnecter(){
Connection con = null;
try {
con = DriverManager.getConnection(getUrl(),getUserName(),getPassword());
logger.info("获取连接成功!");
} catch (Exception e) {
logger.error(e.getMessage(),e);
}
return con;
}
private static String getUrl() {
return "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC&zeroDateTimeBehavior=CONVERT_TO_NULL";
}
private static String getUserName() {
return "test";
}
private static String getPassword() {
return "test@2023";
}
public static List<Map<String,String>> findData(Bean paramBean){
List<Map<String,String>> resultList = new ArrayList<>();
StringBuilder builder = new StringBuilder();
builder.append("select * from ");
builder.append(TABLE_NAME_TASK);
builder.append(" where finishedBy = ? ");
builder.append(" and finishedDate >= ? ");
builder.append(" and finishedDate <= ? ");
builder.append(" order by finishedDate ");
Connection con = null;
PreparedStatement statement = null;
try {
con = ZentaoUtil.getConnecter();
statement = con.prepareStatement(builder.toString());
statement.setString(1,"张三");
statement.setString(2,"2023-01-01");
statement.setString(3,"2023-04-01");
resultList = commonFindData(statement);
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
if(statement!=null){
statement.close();
}
if(con!=null){
con.close();
}
} catch (Exception e2) {
logger.error(e2.getMessage(),e2);
}
}
return resultList;
}
public static List<Map<String,String>> commonFindData(PreparedStatement statement) throws Exception{
ResultSet rs = null;
List<Map<String,String>> resultList = new ArrayList<>();
try {
logger.info("sql语句:"+statement.toString());
rs = statement.executeQuery();
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
while(rs.next()) {
Map<String,String> map = new HashMap<>();
for (int i = 0; i < columnCount; i++) {
String columnName = metaData.getColumnName(i + 1);
Object value = rs.getObject(columnName);
map.put(columnName,value);
}
resultList.add(map);
}
} finally{
if(rs!=null){
rs.close();
}
}
return resultList;
}
}