0

I have successfully exported the csv file of my android application database. Now what i want to do is by browse option selecting i can import that csv file and replace it with existing database tables (like as restore). I have a table in sqlite database name members.

Id  == Name == Phone number
1   == Abhi == 11111111
2   == Ram  == 111111223
3   == Alex == 891273932

I want to restore the csv file in to my phone database in android application.

Thanks

Ramkee
  • 900
  • 1
  • 10
  • 27
Abhishek Punia
  • 291
  • 4
  • 6
  • SQLite supports CSV importing by default. May not work well with complex CSVs though. Read : https://www.sqlite.org/cvstrac/wiki?p=ImportingFiles – C-- Apr 28 '18 at 14:39
  • Please see this link stackoverflow.com/a/72113923/12272687 – Mori May 04 '22 at 13:38

2 Answers2

0

First you have to set separator string, then you can import you csv file to the desired Table.

Here am assuming separator as comma(,)

.separator ","
.import your_csv_file.csv your_table_name

If you use .help, you might notice something interesting :

sqlite> .help
...
.help                  Show this message
.import FILE TABLE     Import data from FILE into TABLE
...
.separator STRING      Change separator used by output mode and .import
...
Ramkee
  • 900
  • 1
  • 10
  • 27
0

Try this:

FileReader file = new FileReader(fileName);
BufferedReader buffer = new BufferedReader(file);
String line = "";
String tableName ="TABLE_NAME";
String columns = "_id, name, phonenumber";
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();

Taken from: Import .csv file to Sqlite in Android

Community
  • 1
  • 1
Steve Kamau
  • 2,755
  • 10
  • 42
  • 73