2016-11-11 104 views
2

我開始學習Java並需要一些幫助。我需要將CSV文件導入SQLite數據庫。我有這個CSV閱讀器,但我不知道如何將這些數據複製到SQLite數據庫。將CSV導入Java中的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(); 
       } 
      } 
     } 

    } 

} 
+0

[這裏](http://stackoverflow.com/questions/25845643/insert-string-into-jdbc-sqlite-database):如何打開一個連接到SQLite數據庫並插入記錄。 – BackSlash

回答

0

如果你的循環保持這樣,你必須遍歷數組的每一行並選擇值並將它們寫入數據庫。要將數據寫入sqlite數據庫,您應該使用google。你會發現如何做到這一點

+0

好的,但我不知道如何結合這2件事情。我可以在這個循環中選擇值並將它們寫入我的數據庫嗎? – bardamu

+0

'爲(字符串str:表){//的getSession()的createQuery( 「INSERT INTO TABLE_NAME VALUES(」 + STR + 「)」)的executeUpdate()}' – XtremeBaumer

+0

類似的東西會做 – XtremeBaumer

0

您可以使用JDBC和準備好的語句(檢查上述文件https://docs.oracle.com/javase/8/docs/api/index.html?java/sql/PreparedStatement.html

  1. 下載一些JDBC驅動程序SQLite的很多例子。例如,這裏https://github.com/xerial/sqlite-jdbc

  2. 添加JDBC罐子到類路徑。

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