将CSV导入Java中的SQLite [英] Import CSV into SQLite in Java

查看:33
本文介绍了将CSV导入Java中的SQLite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Java,需要一些帮助.我需要将CSV文件导入SQLite数据库.我有这个CSV阅读器,但是我不知道如何将这些数据复制到SQLite数据库中.

I'm starting learning Java and need some help. I need to import CSV file into SQLite database. I have this CSV reader, but i don't know how to copy this data into SQLite database.

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 )

You can use JDBC and prepared statements (check this documentation https://docs.oracle.com/javase/8/docs/api/index.html?java/sql/PreparedStatement.html )

  1. 下载一些用于SQLite的JDBC驱动程序.例如,这里 https://github.com/xerial/sqlite-jdbc

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

Add JDBC jar to your classpath.

写这样的东西:

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

这篇关于将CSV导入Java中的SQLite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆