package config;
import com.mysql.cj.xdevapi.JsonArray;
import com.mysql.cj.xdevapi.JsonString;
import utils.JsonObjectUtils;
import java.sql.*;
import java.util.*;
public class MysqlConfig {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://192.168.1.1:3306/next_dfc?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
static final String USER = "";
static final String PASS = "";
public static List<Map> MysqlHandle(String sql) throws ClassNotFoundException, SQLException {
Statement stmt = null;
Class.forName(JDBC_DRIVER);
Connection conn= DriverManager.getConnection(DB_URL,USER,PASS);
List<Map> data = new ArrayList<>();
try{
stmt = conn.createStatement();
ResultSet rs = null;
Integer resultInt = 0;
if(sql.startsWith("select")){
rs = stmt.executeQuery(sql);
data = ResultSetToMap(rs);
}else{
resultInt = stmt.executeUpdate(sql);
HashMap map = new HashMap<String,Integer>();
map.put("resultInt",resultInt);
data.add(map);
}
stmt.close();
conn.close();
}catch(SQLException se){
// 处理 JDBC 错误
se.printStackTrace();
}catch(Exception e){
// 处理 Class.forName 错误
e.printStackTrace();
}finally{
// 关闭资源
try{
if(stmt!=null) stmt.close();
}catch(SQLException se2){
}// 什么都不做
try{
if(conn!=null) conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
return data;
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
String sql;
//ssql = "SELECT name, url FROM t_test_kanban";
sql = "INSERT t_test_kanban SET fid ='8' , name ='ceshi4' , url='woshiurl1' , status ='2'";
List<Map> data = MysqlHandle(sql);
System.out.println(data.size());
}
/*
* ResultSet----->Map
* */
public static List<Map> ResultSetToMap(ResultSet resultSet) throws SQLException {
List<Map> list = new ArrayList<>();
ResultSetMetaData metaData = resultSet.getMetaData();
int columnCount = metaData.getColumnCount();
while (resultSet.next()) {
Map<String, Object> jsonMap = new HashMap<>();
for (int i = 1; i <= columnCount; i++) {
String columnTypeName = metaData.getColumnTypeName(i);
String columnName = metaData.getColumnName(i);
if ("INT".equals(columnTypeName)) {
int anInt = resultSet.getInt(columnName);
jsonMap.put(columnName, anInt);
} else {
String s = resultSet.getString(columnName);
jsonMap.put(columnName, s);
}
}
list.add(jsonMap);
}
return list;
}
}
|