1

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!

3
  • You can try like this ...Have state in an array. Execute a single insert statement inside for loop until this state array finish.. Commented May 15, 2013 at 9:40
  • You can concatenate all the INSERT in one string, then execute one db.execSQL Commented May 15, 2013 at 9:42
  • Subburaj how will i do that? sorry i'm just new in doing this. thanks! Commented May 15, 2013 at 9:52

3 Answers 3

1

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++;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Subburaj!Great help. :)
0

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);

Comments

0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.