Search code examples
javasql-serveropencsv

Insert parse CSV file to SQL Server


I'm parsing CSV file using OpenCSV library. I managed to skip first desired lines, choose only wanted columns and print it to console.
Now I'm struggling with inserting this to MSSQL database.
That's my code for parsing file:

JFileChooser fileopen = new JFileChooser();
    FileFilter filter = new FileNameExtensionFilter(
            "CSV file", "csv");
    fileopen.setFileFilter(filter);

    int ret = fileopen.showDialog(null, "Choose file");
    if (ret == JFileChooser.APPROVE_OPTION) {
        CsvParserSettings settings = new CsvParserSettings();

        settings.detectFormatAutomatically();
        settings.setHeaderExtractionEnabled(true);
        settings.selectIndexes(7, 8, 13, 14);
        settings.setNumberOfRowsToSkip(9);

        List<String[]> rows = new CsvParser(settings).parseAll((fileopen.getSelectedFile()), "UTF-8");
        rows.forEach(arr -> System.out.println(Arrays.toString(arr)));  

Now code

INSERT INTO dbo.Glass(Nr_Temp) values(Arrays.toString(rows.get(1)));

Is getting me whole row instead column (which is understandable:)) but is there any other solution to return columns values to insert them to SQL database?


Solution

  • Thanks Ivan, I removed optimalization as files are small (less then 100 rows each) and also changed

    ps.executeupdate() to `ps.executeBatch()
    

    as it was uploading only last row, now It's working perfect, thank you for your time. Here is my changed code

    try {
    
                PreparedStatement ps = conn.prepareStatement("INSERT INTO dbo.Szyby_temp(nr_zlec_klienta, nr_ref_klienta, szerokosc, wysokosc, ilosc, opis_dodatkowy, data_importu) VALUES(?, ?, ?, ?, ?, ?, getdate())");
                for (String[] row : rows) {
                    int i = 0;
                    for (String columnValue : row) {    
                        ps.setString(++i, columnValue); //Parameter indexes start with 1
                    }
                    ps.addBatch();
                }
                ps.executeBatch(); //if number of rows in csv file is not divisible by maxbatchSize
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e, "ERROR", JOptionPane.ERROR_MESSAGE);
    
            }