I'm trying to transfer the data from a csv file to the database on my app. The csv file wasn't generated from my database, so there are fields that I'm not interested in transferring. How would I go about doing th开发者_开发技巧at?
CSV: date, ref, quantity, type, color, category
DB: date, quantity, color, categoryTry something like this...
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String data = "";
String tableName ="MY_TABLE";
String columns = "date,quantity,color,category";
String InsertString1 = "INSERT INTO " + tableName + " (" + columns + ") values(";
String InsertString2 = ");";
db.beginTransaction();
while ((data = br.readLine()) != null) {
StringBuilder sb = new StringBuilder(InsertString1);
String[] sarray = data.split(",");
sb.append("'" + sarray[0] + "',");
sb.append(sarray[2] + "',");
sb.append(sarray[4] + "',");
sb.append(sarray[5] + "'");
sb.append(InsertString2);
db.execSQL(sb.toString());
}
db.setTransactionSuccessful();
db.endTransaction();
To package static data, use any UI or csv-import command at development time, ship this sqlite db file into asset folder, You can then copy the entire sqlite file onto the device when your application is first run.
To insert a lot of data at run time, bulk insert using transactions is best for performance
You can also use BufferReader
BufferedReader in = new BufferedReader(csvfilepath);
String reader = "";
while ((reader = in.readLine()) != null){
String[] RowData = reader.split(",");
For Java programmer, dbis is useful. You can achieve without single line of code. Check it below.
https://dbisweb.wordpress.com/
精彩评论