gpt4 book ai didi

java - 将 .csvs 插入 Java 中的 SQLite 数据库

转载 作者:IT王子 更新时间:2023-10-29 06:29:58 24 4
gpt4 key购买 nike

大家好。所以我有一组 csv 文件,我想将它们作为表插入到我的 Java 程序中的 sqlite 数据库中。我用谷歌搜索并搜索了 SO,但我找不到任何关于如何将这些 csv 文件插入 sqlite 数据库的教程。我正在使用这个 sqlite 包装器:Zentus SQLiteJDBC .

所以让我们假设我有一个包含以下内容的 csv 文件:

1,John,Doe,5.02,Jane,Smith,5.0

How could I create a table and insert these values into it?

Can anyone point me in the right direction? Thank you!

Update: OK so I found this guide: http://www.sqlite.org/cvstrac/wiki?p=ImportingFiles but the syntax is confusing me a bit. Specifically:

sqlite> create table test (id integer, datatype_id integer, level integer, meaning text);    
sqlite> .separator ","
sqlite> .import no_yes.csv test

我明白这是在做什么,它说分隔符将是一个逗号,并将文件 no_yes.csv 导入到表测试中。然而,这就是我按照 JDBC 指南执行 sql 语句的方式:

Statement stat = conn.createStatement();
stat.executeUpdate("drop table if exists test;");
stat.executeUpdate("create table test (id, name, value);");

我尝试这样做来表示分隔线:

stat.executeUpdate("separator ','");

stat.executeUpdate(".separator ','");

但是两者都给我一个错误。我该怎么做呢?谢谢!

最佳答案

您需要先创建表。然后你可以用类似的东西读取 csv 文件:

BufferedReader br = new BufferedReader(new FileReader("your file"));
String line;
while ( (line=br.readLine()) != null)
{
String[] values = line.split(","); //your seperator

//Convert String to right type. Integer, double, date etc.
stat.executeUpdate("INSERT INTO yourTable VALUES('"+value[0]+"','"+value[1]...
//Use a PeparedStatemant, it´s easier and safer
}
br.close();

关于java - 将 .csvs 插入 Java 中的 SQLite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6004801/

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