【问题标题】:Import CSV into SQLite in Java在 Java 中将 CSV 导入 SQLite
【发布时间】:2017-03-25 17:35:08
【问题描述】:

我开始学习 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();
                }
            }
        }

    }

}

【问题讨论】:

  • HERE: 如何打开与 SQLite 数据库的连接并插入记录。

标签: java sql sqlite csv


【解决方案1】:

您可以使用 JDBC 和预处理语句(查看此文档 https://docs.oracle.com/javase/8/docs/api/index.html?java/sql/PreparedStatement.html

  1. 为 SQLite 下载一些 JDBC 驱动程序。比如这里https://github.com/xerial/sqlite-jdbc

  2. 将 JDBC jar 添加到您的类路径。

  3. 这样写:

    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... }
    

【讨论】:

    【解决方案2】:

    如果您的循环保持这样,您必须遍历数组的每一行并选择值并将它们写入您的数据库。要将数据写入 sqlite 数据库,您应该使用 google。你会发现很多关于如何做到这一点的例子

    【讨论】:

    • 好的,但我不知道如何将这两件事结合起来。我可以在这个循环中选择值并将它们写入我的数据库吗?
    • for(String str : table){//getSession().createQuery("INSERT INTO TABLE_NAME VALUES ("+str+")").executeUpdate()}
    • 这样就可以了
    猜你喜欢
    • 1970-01-01
    • 2013-02-03
    • 2015-09-23
    • 2012-09-14
    • 2011-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    相关资源
    最近更新 更多