更简单的 CSV 到 SQL java 文件转换器
有没有比这更简单的方法将 CSV 文件转换为 SQL 文件?:
BufferedReader input = new BufferedReader(new FileReader(new File("c:\\file.csv")));
Writer output = new BufferedWriter(new FileWriter(new File("c:\\file.sql")));
try {
String line = null;
String[] st = null;
while ((line = input.readLine()) != null) {
st = line.replace("\"","").split(",");
output.write("INSERT INTO `table` "
+ "(`column_id`, `column1`, `column2`) VALUES "
+ "(" + st[2] + ", " + st[0] + ", " + st[1] +")"
+ ";"
+ "COMMIT;\n");
}
} finally {
input.close();
output.close();
}
Is there simpler way to convert CSV files to SQL file than this?:
BufferedReader input = new BufferedReader(new FileReader(new File("c:\\file.csv")));
Writer output = new BufferedWriter(new FileWriter(new File("c:\\file.sql")));
try {
String line = null;
String[] st = null;
while ((line = input.readLine()) != null) {
st = line.replace("\"","").split(",");
output.write("INSERT INTO `table` "
+ "(`column_id`, `column1`, `column2`) VALUES "
+ "(" + st[2] + ", " + st[0] + ", " + st[1] +")"
+ ";"
+ "COMMIT;\n");
}
} finally {
input.close();
output.close();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您找不到更简单的解决方案,请谨慎对 csv 数据进行简单拆分。从经验来看,这是有效的 csv,它将破坏简单的拆分解决方案:
我建议查看诸如 opencsv 之类的库为您处理 csv 解析。
If you don't find a simpler solution be wary of doing a simple split on csv data. Speaking from experience this is valid csv that will break a simple split solution:
I would suggest looking at a library such as opencsv to handle csv parsing for you.
使用现成的 csv 解析器库之一,例如 one。否则,您将需要一个小型状态机来处理带引号的字符串内的逗号等。
我还看到您没有执行 SQL,而是将 sql 语句写入文件。大多数数据库都附带一个加载实用程序,它将接受 csv 文件作为输入。
Use one of the readily available csv parser libraries like this one. Otherwise you will need a small state machine to deal with commas inside quoted strings etc.
I also see that you are not executing the SQL but writing the sql statements to a file. Most databases come with a load utility which will accept a csv file as input.