【问题标题】:SQlite AUTOINCREMENT with Statement Binding带有语句绑定的 SQLite AUTOINCREMENT
【发布时间】:2015-06-08 07:55:05
【问题描述】:

创建了一个表

"CREATE TABLE 学生 (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT,当然是TEXT)”

现在当尝试插入像

这样的行时
String sql = "INSERT INTO student" +" VALUES (?,?)";
SQLiteStatement statement = myWriteableDatabase.compileStatement(sql);
statement.clearBindings();
statement.bindString(2, "Some Name");
statement.bindString(3, "Some Course");
statement.execute();

这会引发异常

table student has 3 columns but 2 values were supplied: , while compiling: INSERT INTO student VALUES (?,?);

即使我已将 id 列设为 AUTOINCREMENT,为什么会出现此异常。

【问题讨论】:

标签: android sql sqlite data-binding


【解决方案1】:

PRIMARY KEY 自动生成仅在将NULL 插入列中时才会启动。

指定要插入的列:

INSERT INTO student(name,course) VALUES ...

id列得到NULL默认值,或者显式插入NULL值,例如

INSERT INTO student VALUES(NULL,?,?)

还要检查您的绑定索引。它们不正确 - 它是查询字符串中 ? 的索引,而不是表中列的索引。

【讨论】:

    【解决方案2】:

    首先,您的bindString 调用中有错误,您的查询中只有2 个? 符号,第一个引用名称列,第二个? 引用课程列。

    如果你想使用这样的查询:

    INSERT INTO student VALUES ('name', 'course')
    

    您需要将代码更改为(请参阅查询):

    String sql = "INSERT INTO student" +" VALUES (NULL, ?,?)";
    SQLiteStatement statement = myWriteableDatabase.compileStatement(sql);
    statement.clearBindings();
    statement.bindString(1, "Some Name");
    statement.bindString(2, "Some Course");
    statement.execute();
    

    或者你可以使用这个查询:

    INSERT INTO student (name, course) VALUES ('first', 'second')
    

    在这种情况下,您可以使用以下代码:

    String sql = "INSERT INTO student (name, course)" +" VALUES (?,?)";
    SQLiteStatement statement = myWriteableDatabase.compileStatement(sql);
    statement.clearBindings();
    statement.bindString(1, "Some Name");
    statement.bindString(2, "Some Course");
    statement.execute();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多