public static Map<String, String[]> parseTable(String tableName) {
List<String> stringType = new ArrayList<>(Arrays.asList("CHAR", "VARCHAR", "TEXT", "DATE", "TIME", "DATETIME", "TIMESTAMP"));
List<String> stringFieldList = new ArrayList<>();
try {
// mysql_sit
String URL = "jdbc:mysql://127.0.0.1:3306/snucs?generateSimpleParameterMetadata=true&allowMultiQueries=true&characterEncoding=utf-8";
String USER = "admin";
String PSWD = "123456";
Connection conn = DriverManager.getConnection(URL, USER, PSWD);
DatabaseMetaData databaseMetaData = conn.getMetaData();
ResultSet specificResultSet = databaseMetaData.getColumns(null, "%", tableName, "%");
String columnName;
String columnType;
while (specificResultSet.next()) {
columnName = specificResultSet.getString("COLUMN_NAME");
columnType = specificResultSet.getString("TYPE_NAME");
if (stringType.contains(columnType) && !stringFieldList.contains(columnName)) {
stringFieldList.add(columnName);
}
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
Map<String, String[]> map = new HashMap<>();
map.put(tableName, stringFieldList.toArray(new String[0]));
return map;
}
public static String json2Sql(JSONObject json, String tableName) {
Map<String, String[]> map = parseTable(tableName);
ArrayList<String> keys = new ArrayList<>();
ArrayList<String> values = new ArrayList<>();
for (Map.Entry<String, Object> entry : json.entrySet()) {
if (entry.getKey().equals("id")) {
continue;
}
keys.add(entry.getKey());
String value = entry.getValue() == null ? null : entry.getValue().toString();
if (Arrays.asList(map.get(tableName)).contains(entry.getKey())) {
if (value != null) {
if (value.indexOf('"') != -1) { // 处理扩展字段包含json情况
value = String.format("\"%s\"", value.replace("\"", "\\\""));
} else {
value = '"' + value + '"'; // 字符串字段给sql语句手动加上双引号
}
}
}
values.add(value);
}
return String.format("insert into %s(%s) values (%s);", tableName, String.join(",", keys), String.join(",", values));
}
@Test
// 一次大概50条左右
void json2sql() {
String jsonArray = "";
List<String> sqlList = Lists.newArrayList();
for (Object json : JSON.parseArray(jsonArray)) {
JSONObject jsonObject = JSON.parseObject(json.toString());
String sql = json2Sql(jsonObject, "sys_user");
sqlList.add(sql);
}
for (String sql : sqlList) {
System.out.println(sql);
}
}
JSON转SQL
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- SQL转GORM 网址:https://www.printlove.cn/tools/sql2gorm[https...
- 首先引入jar包: <dependency> <groupId>com.alibaba</groupId> ...
- 首先给大家带来网上常见的Json字符串转字典,字典转Json字符串代码 Json字符串转字典 字典转Json字符串...
- https://blog.csdn.net/sun6223508/article/details/95042887...