Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

database - Import .csv file to Sqlite in Android

I have a .csv file and I want to import this file putting into my database in android.

Example, the .csv file:

| id | name  | dt1 | dt2 | dt3 | 
| 1  | Paul  | 21  | 98  | 91  |
| 2  | John  | 22  | 44  | 11  |
| 3  | George| 21  | 31  | 22  |
| 4  | Ringo | 20  | 10  | 15  | 

To a thing like that:

Cursor cursor = getWritableDatabase().
rawQuery("Insert into table1(_id, name, dt1, dt2, dt3)
values ( 1, Paul, 21, 98, 91)
values ( 2, John, 22, 44, 11)
values ( 3, George, 21,31,22)
values ( 4, Ringo, 20, 10,15);");

So please, how can I do that?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try following code,

FileReader file = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(file);
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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...