自动生成sql 这是MySQL例子

发布时间 2023-03-27 11:19:01作者: 我的心儿

@Test
public void testGeneSql() {
try {
String ss = getFileContentTwo("D:\test\13json.txt");

        JSONObject jo = JSONObject.parseObject(ss);
        JSONArray ja = jo.getJSONArray("RECORDS");
        System.out.println("JSONArray size = " + ja.size());

        for (int i = 0; i < ja.size(); i++) {
            String content = ja.getJSONObject(i).getString("XML_CONTENT");
            System.out.println("i=" + i + ",size = " + content.length());
            String taskId = ja.getJSONObject(i).getString("RELATION_TASK_ID");
            System.out.println("taskId = " + taskId);
            List<String> splitArray = getSpiltArray(content);
            String sql = buildSql(splitArray, taskId);
            System.out.println(sql);
        }

    } catch (Exception e) {
        System.out.println("error!!!!!!!!!!!");
    }
}

public String getFileContentTwo(String name) throws IOException {
    File file = new File(name);
    // 判断文件是否存在
    if (file.isFile() && file.exists()) {
        // 考虑到编码格式
        InputStreamReader read =
                new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8.toString());
        BufferedReader bufferedReader = new BufferedReader(read);
        StringBuffer stringBuffer = new StringBuffer();
        String lineTxt = null;
        while ((lineTxt = bufferedReader.readLine()) != null) {
            // System.out.println(lineTxt);
            stringBuffer.append(lineTxt);
        }
        read.close();
        return stringBuffer.toString();
    } else {
        System.out.println("该文件不存在");
        return "";
    }
}

//public List<String> buildSql(List<String> splitArray, String taskId) {
public String buildSql(List<String> splitArray, String taskId) {

    StringBuilder strb = new StringBuilder();
    for (int i = 0; i < splitArray.size(); i++) {
        if (0 == i) {
            strb.append("update AUTOMATIC_TASK_DETAIL set xml_content = '").append(splitArray.get(i)).append("where RELATION_TASK_ID='" + taskId + "';\r\n");
        } else {
            strb.append("update AUTOMATIC_TASK_DETAIL set xml_content = '").append(splitArray.get(i)).append("where RELATION_TASK_ID='" + taskId + "';\r\n");
        }

    }
    return strb.toString();

}

public List<String> getSpiltArray(String content) {
    List<String> splitArray = new ArrayList<>();

    int length = content.length();
    if (length <= 3000) {
        splitArray.add(content);
    } else {
        int index = 0;
        while (index < length) {
            String subContent = content.substring(index, index + 3000);
            splitArray.add(subContent);
            index += 3000;
        }
    }

    return splitArray;
}