我正在开始学习 Java,需要一些帮助。我需要将 CSV 文件导入 SQLite 数据库。我有这个 CSV 阅读器,但我不知道如何将此数据复制到 SQLite 数据库中。
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class csv {
public static void main(String[] args) {
String csvFile = "/home/user/user.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
String[] table = line.split(cvsSplitBy);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
您可以使用 JDBC 和准备好的语句(查看此文档https://docs.oracle.com/javase/8/docs/api/index.html?java/sql/PreparedStatement.html )
下载一些适用于 SQLite 的 JDBC 驱动程序。例如,这里https://github.com/xerial/sqlite-jdbc
将 JDBC jar 添加到您的类路径中。
-
写这样的东西:
String dbName = "insert your db name here";
Connection conn = null;
try {
// use your dbname instead
conn = DriverManager.getConnection("jdbc:sqlite:dbname");
// use your tablename instead; set as much question marks as many fields you have
PreparedStatement stmt =
conn.prepareStatement("insert into tablename (column1, column2, column3) values (?, ?, ?)");
br = ...;
while (line = ...) {
String[] table = ...;
// set values to replace question marks in prepared statement
stmt.setInt(1, table[0]);
stmt.setString(2, table[1]);
stmt.setString(3, table[2]);
// so, know your statement is like insert into ... values (table[0], table[1], table[2])
// and maybe add other fields...
stmt.executeUpdate(); // insert data into table
}
} catch (...) { ...
} finally { ...close conn and br... }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)