Reputation: 1719
in my Application I am using an SQLite Database. This Database get's created by a DBHelper-class, if it isn't created yet.
Initially I need a table with about 30 Rows. What is the best practice, to fill it with data? Here is my code. It works nicely, but I think there is a better way of doing it?
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context){
super(context, DATABASE_NAME , null, 1);
}
private static final String DATABASE_TABLE_QUOTES = "quotes";
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE_QUOTES = "CREATE TABLE IF NOT EXISTS `" + DATABASE_TABLE_QUOTES + "` (\n" +
"\t`quote_id`\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
"\t`quote`\tTEXT NOT NULL\n" +
");";
db.execSQL(CREATE_TABLE_QUOTES);
db.execSQL("INSERT INTO " + DATABASE_TABLE_QUOTES + "VALUES (1, 'test 1')");
db.execSQL("INSERT INTO " + DATABASE_TABLE_QUOTES + "VALUES (2, 'test 2')");
db.execSQL("INSERT INTO " + DATABASE_TABLE_QUOTES + "VALUES (3, 'test 3')");
db.execSQL("INSERT INTO " + DATABASE_TABLE_QUOTES + "VALUES (4, 'test 4')");
// ........
}
}
Upvotes: 2
Views: 1075
Reputation: 5795
Since you have asked for best practice, I am referencing this answer
You should use statements
database.beginTransaction();
SQLiteStatement stmt = database.compileStatement(sql);
for (int i = 0; i < NUMBER_OF_ROWS; i++) {
//generate some values
stmt.bindString(1, randomName);
stmt.bindString(2, randomDescription);
stmt.bindDouble(3, randomPrice);
stmt.bindLong(4, randomNumber);
long entryID = stmt.executeInsert();
stmt.clearBindings();
}
database.setTransactionSuccessful();
database.endTransaction();
Reference
Here is one more link where a comparison between these two insertion methods is given. (for 100 records, normal insertion took 1657ms, while statements with endTransaction()
took 92ms)
Upvotes: 2
Reputation: 382
You can try the following method.
ContentValues values=new ContentValues();
values.put(1, "test1");
db.insert("table_name", null, values);
values.put(2, "test2");
db.insert("table_name", null, values);
values.put(3,"test3");
db.insert("table_name", null, values);
values.put(4,"test4");
db.insert("table_name", null, values);
...
for more details check these links
http://mrbool.com/how-to-insert-data-into-a-sqlite-database-in-android/28895
How to insert value in data base using sqlite in android?
Upvotes: 3