SQLite autoincrement - How to insert values?

喜你入骨 提交于 2019-11-26 20:05:32

问题


I generate a SQLite table (in java):

create table participants (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, col1,col2);

afterwards I try to add rows using the INSERT comand:

insert into participants values ("bla","blub");

i get the error:

java.sql.SQLException: table participants has 3 columns but 2 values were supplied

I thought the row id would be generated automatically, but it seems that I miss anything.


I tried another solution:

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();

as result I received a null pointer exception at "prep.setInt(1,n);"

Do you see the fault?


回答1:


Have you tried indicating to which fields of the table the parameters you are passing are supposed to be related?

INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

In your case maybe something like:

INSERT INTO participants(col1, col2) VALUES ("bla","blub");



回答2:


Easiest way without using column names will be using null in the place of autoincreament is like this

insert into table values (null, col1, col2)

if you have already set the first column as autoincrement, it will work fine.




回答3:


found a working solution here:

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



回答4:


The reason to your error is that SQL Inserts expect you to provide the same number of values as there are columns in the table when a column specifier is not used.

i.e. when you write a SQL query like this:

INSERT INTO TableName VALUES(a1,a2, ...)

.. the values have to be in the exact same order as in the table definition (and also the same amount). The reason for this is to avoid ambiguity and reduce the numbers of errors.

In your case you have an auto increment column which you don't want to specify a value for. That is of course possible, but following the rules above you need to specify column names:

INSERT INTO TableName (columnName1, columnName2) VALUES(Value1, Value2);


来源:https://stackoverflow.com/questions/8250814/sqlite-autoincrement-how-to-insert-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!