Multiple android sqlite insert statements

I have 800 insert statements downloaded from the network in the following format:

insert into mytable(col1,..,coln) values(val1,..valn);insert into mytable col...

I heard about ContentValue transactions and using union , but I can't figure out which one is better for this case.

What is the best way to insert them into sqlite database after trimming mytable ?

+6
source share
2 answers

If you run multiple queries, you should use transactions to improve data integrity and performance. This is the code that will give you an idea of โ€‹โ€‹how to do this:

  SQLiteDatabase db = sqlHelper.getWritableDatabase(); // get a writable database here db.beginTransaction(); try { for (int insertQuery : listOfQueries) { // loop through your records db.insert(...); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } db.close(); 
+17
source

I use the code below, I run only one request.

  public void addListRecord(List<Province> list) { SQLiteDatabase db = DatabaseManager.getInstance().openDatabase(); try { String sql = " INSERT INTO " + TABLE_PROVINCE + " (" + COL_PROVINCE_ID + "," + COL_PROVINCE_NAME + "," + COL_PROVINCE_STATUS + ") VALUES "; String value = ""; for (Province item : list) { value += "('" + item.getId() + "'," + "'" + item.getName() + "'," + "'" + item.getStatus() + "')"; value += ","; } value = Utils.removeLastChar(value); value += ";"; String mQuery = sql + value; Logger.debug("mQuery: " + mQuery); SQLiteStatement statement = db.compileStatement(mQuery); statement.execute(); } catch (SQLException e) { Logger.debug("SQLException Error: " + e); } finally { DatabaseManager.getInstance().closeDatabase(); } } public static String removeLastChar(String s) { if (s == null || s.length() == 0) { return s; } return s.substring(0, s.length() - 1); } 
0
source

Source: https://habr.com/ru/post/958193/


All Articles