假装我有一个包含2列的表格。 _id和名字。 _id是主键,我不想手动设置此值。我想执行name =“john”的插入,让程序创建我自己的_id。我不清楚在插入时使用什么“索引”以及要使用多少个问号。这段代码能完成这项工作吗? john的索引应该是1还是2?
String TABLENAME = "table";
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?);");
statement.bindString(1,"john");
statement.executeInsert();
接下来,说我想手动设置我自己的_id值。我会将代码更改为:
String TABLENAME = "table";
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(?,?);");
statement.bindLong(1,666); //Manual _id.
statement.bindString(2,"john");
statement.executeInsert();
答案 0 :(得分:3)
您只提供名称的第一个示例将不起作用:
sqlite> create table test (i integer primary key autoincrement, j text);
sqlite> insert into test values ('asd');
Error: table test has 2 columns but 1 values were supplied
sqlite> insert into test values (null, 'asd');
sqlite> select * from test;
1|asd
sqlite> insert into test (j) values ('asd');
sqlite> select * from test;
1|asd
2|asd
所以你需要以这种方式将name列标识为唯一值的目标,(或者你在评论中提到的传递null):
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" (name) VALUES(?);");
你的第二个例子应该可以正常工作。
这适用于以这种方式创建的某些表:
create table SomeTable (_id integer primary key autoincrement, name text)
答案 1 :(得分:3)
然后
SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(null,?);");
statement.bindString(1,"john");
也应该有效。