我的sql脚本文件包含所有插入语句,如下所示
Cache-Control
如何将每个参数单独存储到ArrayList中,如下所示
INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES
(1, 'Madhava'),
(2, 'Rao'),
(3, 'Tmr');
INSERT INTO PUBLIC.ADDRESS(ID, CITY) VALUES
(1, 'Bangalore'),
(2, 'Chirala'),
(3, 'Pune');
我如何解析sql文件并将每个语句单独存储到Arraylist中,如上所述?
答案 0 :(得分:0)
让我们假设我们有
String data =
" INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES\r\n"
+ " (1, 'Madhava'),\r\n" + " (2, 'Rao'),\r\n"
+ " (3, 'Tmr'); \r\n" + "\r\n"
+ " INSERT INTO PUBLIC.ADDRESS(ID, CITY) VALUES\r\n"
+ " (1, 'Bangalore'),\r\n" + " (2, 'Chirala'),\r\n"
+ " (3, 'Pune'); ";
List<String> inserts = new ArrayList<>();
Scanner sc = new Scanner(data); //you can also use new Scanner(new File("location/of/your/textfile.sql"));
您的解决方案可能看起来像(我们使用空行将数据分成几个部分):
String command = "";
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
if (line.isEmpty() || command.isEmpty()) {
command = line;
} else {
String values = line.replaceAll(",$", ";");//replace `,` at the end with ;
inserts.add(command + " " + values);
}
}
或者更简单(我们只需将命令设置为以&#34开头的行; INSERT&#34;并创建命令和非空行的连接):
String command = "";
while (sc.hasNextLine()) {
String line = sc.nextLine().trim();
//ignore empty lines
if (!line.isEmpty()) {
if (line.startsWith("INSERT ")) {
command = line;
} else {
//lets change `),` to `);`
String values = line.replaceAll(",$", ";");
inserts.add(command + " " + values);
}
}
}