Reputation: 69
Is there an easier way I can insert data in a table in SQLite? What I need is to insert State_ID and State_Name in Table tblState. Since there are a lot of State in US, is there another way I can use instead of this:
String ROW1 = "INSERT INTO tblState VALUES (1,'Alabama')";
String ROW2 = "INSERT INTO tblState VALUES (2,'Alaska')";
String ROW3 = "INSERT INTO tblState VALUES (3,'California')";
db.execSQL(ROW1);
db.execSQL(ROW2);
db.execSQL(ROW3);
Thanks!
Upvotes: 1
Views: 1753
Reputation: 5192
Try for this..
String state[] = { "state1" , "state2",.............};
int id=1;
for(int i=0;i<state.length;i++)
{
db.execSQL("INSERT INTO tblState VALUES (id,state[i])");
id++;
}
Upvotes: 1
Reputation: 3814
You should use ContentValues
for each of the rows you want to insert:
ContentValues values = new ContentValues();
values.put('State_ID', 1);
values.put('State_Name', "Alabama");
and then use db.insert("tblState", null, values)
to insert the row. You can write a method to construct your ContentValues:
public ContentValues method(int id, String name) {
ContentValues values = new ContentValues();
values.put('State_ID', id);
values.put('State_Name', name);
}
Your code will be:
db.insert("tblState", null, method(1, "Alabama"));
db.insert("tblState", null, method(2, "Alaska"));
db.insert("tblState", null, method(3, "California"));
Or just loop through all the states...
Upvotes: 0
Reputation: 56429
You can do the following:
String ALLROWS = "INSERT INTO tblState"
+ "SELECT 1 AS 'State_ID', 'Alabama' AS 'State_Name'"
+ "UNION SELECT 2 AS 'State_ID', 'Alaska' AS 'State_Name'"
+ "UNION SELECT 3 AS 'State_ID', 'California' AS 'State_Name'";
db.execSQL(ALLROWS);
Upvotes: 0