Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return autoincrement value in insert query in SQLite?

In my project I use System.Data.SQLite. Database has table Tags, which contains autoincrement primary field ID (type Integer). When I write:

using (SQLiteCommand command = conn.CreateCommand())
{
   command.CommandText = "insert into Tags(name) values(@name) returning into @id";
   command.Parameters.Add("@id", DbType.Int32).Direction = ParameterDirection.Output;
   command.ExecuteNonQuery();
}

Visual Studio said that the operation is not supported. How to fix it?

Error occurs on line:

command.Parameters.Add("@id", DbType.Int32).Direction = ParameterDirection.Output;
like image 936
Anton Kandybo Avatar asked Sep 30 '10 05:09

Anton Kandybo


People also ask

Does SQLite support Autoincrement?

SQLite AUTOINCREMENT is a keyword used for auto incrementing a value of a field in the table. We can auto increment a field value by using AUTOINCREMENT keyword when creating a table with specific column name to auto increment.

How does Autoincrement work in SQLite?

AUTOINCREMENT guarantees that automatically chosen ROWIDs will be increasing but not that they will be sequential. Because AUTOINCREMENT keyword changes the behavior of the ROWID selection algorithm, AUTOINCREMENT is not allowed on WITHOUT ROWID tables or on any table column other than INTEGER PRIMARY KEY.

What does SQLite INSERT return?

In the INSERT statement above, SQLite computes the values for all three columns. The RETURNING clause causes SQLite to report the chosen values back to the application. This saves the application from having to issue a separate query to figure out exactly what values were inserted.

When you INSERT a new row into a SQLite database it automatically generates a value for?

If you don't specify the rowid value or you use a NULL value when you insert a new row, SQLite automatically assigns the next sequential integer, which is one larger than the largest rowid in the table. The rowid value starts at 1.


2 Answers

I found working query:

SELECT last_insert_rowid()
like image 56
Anton Kandybo Avatar answered Oct 13 '22 02:10

Anton Kandybo


SQLite 3.35.0 and newer supports RETURNING clause:

The RETURNING clause is designed to provide the application with the values of columns that are filled in automatically by SQLite.

The code could look like:

INSERT INTO Tags(name) VALUES(@name) RETURNING ID;
like image 42
Lukasz Szozda Avatar answered Oct 13 '22 01:10

Lukasz Szozda