使用io流将insert语句修改为delete语句,delete语句使用主键作为删除条件,并将结果输出到文件中
import java.io.*;
public class MyInsertToDelete {
public static void main(String[] args) {
// 文件路径
String filePath = "D:/b.sql";
File file = new File(filePath);
//字符输入流进行读取操作读取
BufferedReader reader = null;
// 每次写入一行
FileWriter writer = null;
//每一行的内容
String tempString = null;
// 行号
int line = 1;
try {
writer = new FileWriter("D:/a.sql");
//输入字节流,FileInputStream主要用来操作文件输入流
FileInputStream intput = new FileInputStream(file);
// System.out.println("以行为单位读取文件内容,一次读一整行:")
//InputStreamReader是转换流,将字节流转成字符流
reader = new BufferedReader(new InputStreamReader(intput));
while ((tempString = reader.readLine()) != null) {
writer.write(convert(tempString)+";\n");
//System.out.println(convert(tempString));
//System.out.println(tempString);
writer.write(tempString+"\n");
line++;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static String convert(String sql) {
String result = "DELETE FROM ";
sql = sql.toUpperCase();
sql = sql.replace("INSERT INTO ", "");
String table = sql.substring(0, sql.indexOf("("));
sql = sql.replace(table, "").replace("'", "");
String[] values = sql.split("VALUES");
String[] k = values[0].replace("(", "").replace(")", "").split(",");
String[] v = values[1].replace("(", "").replace(")", "").split(",");
result += table + " WHERE ";
result += k[0] + "=" + "'" + v[0] + "'";
return result;
}
}