有没有更简单的方法可以在SQLite中的表中插入数据?我需要的是在表tblState中插入State_ID和State_Name。既然美国有很多州,那么我可以用另一种方式代替吗:
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);
谢谢!
答案 0 :(得分:1)
试试这个..
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++;
}
答案 1 :(得分:0)
您可以执行以下操作:
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);
答案 2 :(得分:0)
您应该为要插入的每一行使用ContentValues
:
ContentValues values = new ContentValues();
values.put('State_ID', 1);
values.put('State_Name', "Alabama");
然后使用db.insert("tblState", null, values)
插入行。您可以编写一个方法来构建ContentValues:
public ContentValues method(int id, String name) {
ContentValues values = new ContentValues();
values.put('State_ID', id);
values.put('State_Name', name);
}
您的代码将是:
db.insert("tblState", null, method(1, "Alabama"));
db.insert("tblState", null, method(2, "Alaska"));
db.insert("tblState", null, method(3, "California"));
或者只是循环遍历所有州......