2016-11-11 105 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... }