Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simpler CSV to SQL java file converter

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();
}
like image 274
MatBanik Avatar asked Sep 08 '26 17:09

MatBanik


1 Answers

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.

like image 83
javamonkey79 Avatar answered Sep 10 '26 07:09

javamonkey79



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!