SQLite自动增量 - 如何插入值?

Ant*_*hea 44 java sqlite auto-increment

我生成一个SQLite表(在java中):

create table participants (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, col1,col2);
Run Code Online (Sandbox Code Playgroud)

之后我尝试使用INSERT命令添加行:

insert into participants values ("bla","blub");
Run Code Online (Sandbox Code Playgroud)

我收到错误:

java.sql.SQLException: table participants has 3 columns but 2 values were supplied
Run Code Online (Sandbox Code Playgroud)

我以为行ID会自动生成,但似乎我错过了任何东西.


我试过另一个解决方案

PreparedStatement prep = conn.prepareStatement("insert into participants values (?,?,?);");
Integer n = null;
prep.setInt(1,n);
prep.setString(2, "bla");
prep.setString(3, "blub");
prep.addBatch();
prep.executeBatch();
Run Code Online (Sandbox Code Playgroud)

结果我收到了"prep.setInt(1,n);"的空指针异常.

你看到了错吗?

set*_*eth 58

您是否尝试过表明您传递的参数与表的哪些字段相关?

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
Run Code Online (Sandbox Code Playgroud)

在你的情况下可能是这样的:

INSERT INTO participants(col1, col2) VALUES ("bla","blub");
Run Code Online (Sandbox Code Playgroud)


Pad*_*dhu 19

不使用列名称的最简单方法是在autoincreament中使用null就像这样

insert into table values (null, col1, col2)
Run Code Online (Sandbox Code Playgroud)

如果你已经将第一列设置为自动增量,它将正常工作.


Ant*_*hea 8

找到工作的解决方案在这里:

PreparedStatement prep = conn.prepareStatement("insert into participants values ($next_id,?,?);");
prep.setString(2, "bla");
prep.setString(3, "blub");
Run Code Online (Sandbox Code Playgroud)