gpt4 book ai didi

java - 在 Java 中将数据从 CSV 导入到 SQLite 表

转载 作者:行者123 更新时间:2023-12-02 13:23:52 25 4
gpt4 key购买 nike

我有一个包含 500K 条记录的 .csv 文件,其中每条记录都有 4 列。我希望将所有这些记录导入到 Java (JDBC) 中的 SQLite 表中。

我尝试过使用 executeUpdate()executeBatch(),但这两个方法都非常慢。他们每分钟处理 400-500 条记录。

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.sql.*;

public class MyClass{
public static void main(String[] args) throws FileNotFoundException, ParseException, SQLException, ClassNotFoundException{
Connection c = null;
Statement stmt = null;
try {
Class.forName("org.sqlite.JDBC");
c = DriverManager.getConnection("jdbc:sqlite:mydb.db");
stmt = c.createStatement();
String drop_sql = "DROP TABLE IF EXISTS MyTable";
stmt.executeUpdate(drop_sql);
String create_sql = "CREATE TABLE MyTable " +
"(VAR1 CHAR(50) NOT NULL, " +
"VAR2 CHAR(10) PRIMARY KEY NOT NULL," +
" VAR3 TEXT NOT NULL, " +
" VAR4 TEXT NOT NULL )";

stmt.executeUpdate(create_sql);
File premFile = new File("MyFile.csv");
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Scanner scanner = new Scanner(premFile);
scanner.useDelimiter(",");
int i = 0, count = 500000;

while (i < count){
String myRecord = scanner.nextLine();
String[] cols = myRecord.split(",");
String var1 = cols[0];
String var2 = cols[1];
Date var3 = df.parse(cols[2]);
Date var4 = df.parse(cols[3]);

String query = "INSERT INTO MyTable VALUES (" +
"'" + var1 + "', " +
"'" + var2 + "', " +
"'" + var3 + "', " +
"'" + var4 + "')";
stmt.addBatch(query);
i++;
}
stmt.executeBatch();
stmt.close();
c.close();
} catch ( Exception e ) {
System.err.println( e.getClass().getName() + ": " + e.getMessage() );
System.exit(0);
}
}
}

如果我采用 SQLite 方式,并使用 .import my_file.csv my_table 将 csv 导入表中,我可以在几秒钟内完成完整的任务。有没有什么方法可以仅使用 Java 代码来实现类似的性能?

我尝试了 PreparedStatement,但它没有明显的改进。

最佳答案

我认为你最大的问题可能是你在每次迭代时都要返回到文件,我会尝试将行加载到数组中并从那里进行处理。

附注您可能不想使用 scanner.useDelimiter(",") 因为您无论如何都在使用 scanner.nextLine() 而不是 scanner.next().我相信这没有任何作用,尽管我这样说可能不正确,但请尝试一下。

关于java - 在 Java 中将数据从 CSV 导入到 SQLite 表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43462687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com