简体   繁体   中英

Import CSV into SQLite in Java

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();
                }
            }
        }

    }

}

if your loop stays like this you have to iterate through the array each line and pick the values and write them to your database. to write data to a sqlite database you should use google. you will find plenty examples on how to do that

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. Download some JDBC driver for SQLite. For example, here https://github.com/xerial/sqlite-jdbc

  2. Add JDBC jar to your classpath.

  3. Write something like that:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM