You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
admin-client-temperature/src/main/java/com/rehome/mqttclienttemperature/utils/JdbcUtil.java

96 lines
3.6 KiB
Java

1 year ago
package com.rehome.mqttclienttemperature.utils;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rehome.mqttclienttemperature.datasource.DataSource;
import com.rehome.mqttclienttemperature.dto.ResponseDto;
import lombok.extern.slf4j.Slf4j;
import java.sql.*;
12 months ago
import java.text.SimpleDateFormat;
1 year ago
import java.util.ArrayList;
import java.util.List;
11 months ago
import java.util.Locale;
1 year ago
@Slf4j
public class JdbcUtil {
/**
* sql
*
* @param datasource
* @param sql
*/
public static ResponseDto executeSql(DataSource datasource, String sql) {
return executeSql(datasource,sql,new ArrayList<Object>());
}
/**
* sql
*
* @param datasource
* @param sql
* @param jdbcParamValues
*/
public static ResponseDto executeSql(DataSource datasource, String sql, List<Object> jdbcParamValues) {
log.info(sql);
log.info(JSON.toJSONString(jdbcParamValues));
DruidPooledConnection connection = null;
try {
connection = PoolManager.getPooledConnection(datasource);
PreparedStatement statement = connection.prepareStatement(sql);
for (int i = 1; i <= jdbcParamValues.size(); i++) {
statement.setObject(i, jdbcParamValues.get(i - 1));
}
boolean hasResultSet = statement.execute();
if (hasResultSet) {
ResultSet rs = statement.getResultSet();
int columnCount = rs.getMetaData().getColumnCount();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= columnCount; i++) {
String columnName = rs.getMetaData().getColumnLabel(i);
columns.add(columnName);
}
List<JSONObject> list = new ArrayList<>();
while (rs.next()) {
JSONObject jo = new JSONObject();
columns.stream().forEach(t -> {
try {
11 months ago
// if(t.equals("create_date")){
// Timestamp timestamp = rs.getTimestamp("create_date");
// Date date = new Date(timestamp.getTime());
// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// jo.put(t, sdf.format(date));
// }else{
12 months ago
Object value = rs.getObject(t);
11 months ago
String key = t;
String keyLow = key.toLowerCase(Locale.ROOT);
jo.put(keyLow, value);
//}
1 year ago
} catch (SQLException e) {
e.printStackTrace();
}
});
list.add(jo);
}
return ResponseDto.apiSuccess(list);
} else {
int updateCount = statement.getUpdateCount();
return ResponseDto.apiSuccess("sql修改数据行数" + updateCount);
}
} catch (Exception e) {
e.printStackTrace();
return ResponseDto.fail(e.getMessage());
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}