我正在使用OpenCSV库解析CSV文件。我设法跳过第一个所需的行,只选择想要的列并将其打印到控制台 现在我正在努力将其插入到MSSQL数据库中 这是我解析文件的代码:
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)));
现在代码
INSERT INTO dbo.Glass(Nr_Temp) values(Arrays.toString(rows.get(1)));
让我整行而不是列(这是可以理解的:))但是有没有其他解决方案来返回列值以将它们插入SQL数据库?
答案 0 :(得分:1)
已更新
您需要遍历String[]
以访问列的每个单独值。
PreparedStatement ps = connection.prepareStatement("INSERT INTO dbo.Szyby_temp(nr_zlec_klienta, nr_ref_klienta, szerokosc, wysokosc, ilosc, opis_dodatkowy, data_importu) VALUES(?, ?, ?, ?, ?, ?, getdate())");
int maxBatchSize = 100; //Using batching for performance
int currentBatchSize = 0;
for (String[] row : rows) {
int i = 1;
for (String columnValue : row) {
ps.setString(i++, columnValue); //Parameter indexes start with 1
}
ps.addBatch();
if (++currentBatchSize % maxbatchSize == 0) {
ps.executeUpdate();
}
}
ps.executeUpdate(); //if number of rows in csv file is not divisible by maxbatchSize
答案 1 :(得分:0)
感谢Ivan,我删除了最佳化,因为文件很小(每个少于100行)并且也已更改
ps.executeupdate() to `ps.executeBatch()
因为它只上传了最后一行,现在它工作得很完美,谢谢你的时间。 这是我更改的代码
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);
}