Simplified CSV to SQL Java File Converter

Is there an easier 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();
}
+3
source share
2 answers

If you do not find a simpler solution, be wary of making a simple split on csv data. From experience, this is a 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 like opencsv to handle csv parsing for you.

+1
source

csv, . ..

, SQL, sql . , csv .

+1

Source: https://habr.com/ru/post/1775348/


All Articles