2014-12-03 81 views
0

如何在android上導入csv到sqlite並列出信息。我是新來的Andorid和一個完整的示例將是巨大的,我理解它是如何工作的,DB赫普勒是我的問題,我不知道如何先設置它發現這樣的代碼如何在Android上導入csv到sqlite並列出信息

   InputStream is = getAssets().open("textv.csv"); 
       BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 

       String line = ""; 
       String tableName ="TABLE_NAME"; 
       String columns = "_id, name, dt1, dt2, dt3"; 
       String str1 = "INSERT INTO " + tableName + " (" + columns + ") values("; 
       String str2 = ");"; 

       db.beginTransaction(); 
       while ((line = buffer.readLine()) != null) { 
        StringBuilder sb = new StringBuilder(str1); 
        String[] str = line.split(","); 
        sb.append("'" + str[0] + "',"); 
        sb.append(str[1] + "',"); 
        sb.append(str[2] + "',"); 
        sb.append(str[3] + "'"); 
        sb.append(str[4] + "'"); 
        sb.append(str2); 
        db.execSQL(sb.toString()); 
       } 
       db.setTransactionSuccessful(); 
       db.endTransaction(); 

,請幫助

回答

0

您是否面臨該代碼段的任何問題?你最好使用ContentValues而不是StringBuilder。

InputStream is = getAssets().open("textv.csv"); 
BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); 

String line = ""; 
String tableName ="TABLE_NAME"; 
String columns = "_id, name, dt1, dt2, dt3"; 
ContentValues values = new ContentValues(); 
db.beginTransaction(); 
while ((line = buffer.readLine()) != null) 
{ 
    values.clear(); 
    String[] str = line.split(","); 

    values.put ("_id", str[0]); 
    values.put ("name", str[1]); 
    values.put ("dt1", str[2]); 
    values.put ("dt2", str[3]); 
    values.put ("dt3", str[4]); 

    db.insert (tableName, null, values); 
} 

db.setTransactionSuccessful(); 
db.endTransaction(); 

請注意,我還沒有添加任何錯誤處理代碼。

+0

我可以得到這一切運行這只是我發現的代碼的一部分,但我想看到這個想法的整個概念如何做到這一點 – 2014-12-03 21:38:40