Mysql转储字符转义和CSV读取



我正试图将mysql查询的内容转储到csv中,并使用一些基于java的开源csv阅读器进行读取。以下是我面临的问题,

  1. 我的数据集大约有50个字段。数据集包含的字段很少,其文本具有换行符。因此,为了防止破坏我的CSV阅读器,我给Fields提供了可选的用"\"括起来的选项,这样换行符就会被包裹在双引号中。在这种情况下,对于其他字段,即使没有换行符,它也会将它们包裹在双引引号中
  2. 在进行mysql转储时,默认情况下转义符是\(反斜杠)。这会导致换行符在末尾出现\,从而中断csv解析器。要在末尾删除此\,如果我给Fields转义符为"(空字符串),它会导致文本中的双引号无法转义,仍然会破坏csv读取

如果我可以跳过换行转义,但仍然保留转义双引号,以使csv阅读器不会中断,那就太好了。

有什么建议我可以在这里遵循吗?

谢谢,Sriram

尝试使用uniVocity解析器将数据转储到CSV中。然后,您可以使用相同的库读取结果:

尝试将数据转储出去:

ResultSet resultSet = executeYourQuery();
// To dump the data of our ResultSet, we configure the output format:
CsvWriterSettings writerSettings = new CsvWriterSettings();
writerSettings.getFormat().setLineSeparator("n");
writerSettings.setHeaderWritingEnabled(true); // if you want want the column names to be printed out.
// Then create a routines object:
CsvRoutines routines = new CsvRoutines(writerSettings);
// The write() method takes care of everything. Both resultSet and output are closed by the routine.
routines.write(resultSet, new File("/path/to/your.csv"), "UTF-8");

这个来读取你的文件:

// creates a CSV parser
CsvParserSettings parserSettings = new CsvParserSettings();
parserSettings.getFormat().setLineSeparator("n");
parserSettings.setHeaderExtractionEnabled(true); //extract headers from file
CsvParser parser = new CsvParser(parserSettings);
// call beginParsing to read records one by one, iterator-style. Note that there are many ways to read your file, check the documentation.
parser.beginParsing(new File("/path/to/your.csv"), "UTF-8);
String[] row;
while ((row = parser.parseNext()) != null) {
System.out.println(Arrays.toString(row));
}

希望这能有所帮助。

免责声明:我是这个库的作者,它是开源和免费的(Apache V2.0许可证)

最新更新