SQLite autoincrement - How to insert values?

JavaSqliteAuto Increment

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

found a working solution here:

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

Solution 4 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAntheaView Question on Stackoverflow
Solution 1 - JavasethView Answer on Stackoverflow
Solution 2 - JavaPadhuView Answer on Stackoverflow
Solution 3 - JavaAntheaView Answer on Stackoverflow
Solution 4 - JavajgauffinView Answer on Stackoverflow