更简单的 CSV 到 SQL java 文件转换器

发布于 2024-10-03 01:46:48 字数 668 浏览 0 评论 0原文

有没有比这更简单的方法将 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

平定天下 2024-10-10 01:46:48

如果您找不到更简单的解决方案,请谨慎对 csv 数据进行简单拆分。从经验来看,这是有效的 csv,它将破坏简单的拆分解决方案:

"field 1a, field 1b", field2, "field 3a, field3b", field4

我建议查看诸如 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:

"field 1a, field 1b", field2, "field 3a, field3b", field4

I would suggest looking at a library such as opencsv to handle csv parsing for you.

儭儭莪哋寶赑 2024-10-10 01:46:48

使用现成的 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文