【问题标题】:SQLite and Android Insert/Updates on SQLiteDatabase -CompiledStatements-SQLiteDatabase 上的 SQLite 和 Android 插入/更新 -CompiledStatements-
【发布时间】:2011-07-15 06:05:38
【问题描述】:

假设我有一张有 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();

【问题讨论】:

  • @Sandy:不,第一个示例不应该也不起作用。 sqlite 不会“猜测”提供的值将放在第二列中。
  • @sixfeetsix 在 SQLite 文档中,它说如果将空值作为主键传递,那么 SQLite 将自动创建一个键。因此,如果有一个问号,我会假设它会解释为我将 null 传递给键,然后将“john”传递给技术上的第二个参数(列“名称”)。无论如何,我想我认为手动处理所有列更容易,然后第一列传递 null。这将自动创建主键并让我传递任何其他值,并且将来允许我手动使用自己的键。
  • @user817129:请参阅我的更新以获取有关如何传递或不传递自动增量列的值的示例。
  • 我明白了。我将使用列名并相应地传递值。

标签: android sqlite insert compilation


【解决方案1】:

您仅提供名称的第一个示例将不起作用:

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)

【讨论】:

    【解决方案2】:

    然后

        SQLiteStatement statement = db.compileStatement("INSERT INTO "+TABLENAME+" VALUES(null,?);");
        statement.bindString(1,"john");
    

    应该也可以。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多