The last line is important. Why do I supply a connection? Well there is a SQLite function called last_insert_rowid() that you can call and get the last insert ID. Problem is it is bound to a connection and .NET seems to be reopening and closing connections for every dataset operation. I thought getting the connection from a table adapter would change things. But it doesn't.
Would anyone know how to solve this? Maybe where to get a constant connection from? Or maybe something more elegant?
Thank you.
EDIT:
This is also a problem with transactions, I would need the same connection if I would want to use transactions, so that is also a problem...
回答1:
select last_insert_rowid();
And you will need to execute it as a scalar query.
string sql =@"select last_insert_rowid()";long lastId =(long)command.ExecuteScalar(sql);// Need to type-cast since `ExecuteScalar` returns an object.
回答2:
Using C# (.net 4.0) with SQLite, the SQLiteConnection class has a property LastInsertRowId that equals the Primary Integer Key of the most recently inserted (or updated) element.
The rowID is returned if the table doesn't have a primary integer key (in this case the rowID is column is automatically created).
As for wrapping multiple commands in a single transaction, any commands entered after the transaction begins and before it is committed are part of one transaction.
long rowID;using(SQLiteConnection con =newSQLiteConnection([datasource]){SQLiteTransaction transaction =null; transaction = con.BeginTransaction();...[execute insert statement] rowID = con.LastInsertRowId; transaction.Commit()}
回答3:
last_insert_rowid() is part of the solution. It returns a row number, not the actual ID.
cmd = CNN.CreateCommand(); cmd.CommandText="SELECT last_insert_rowid()";object i = cmd.ExecuteScalar(); cmd.CommandText="SELECT "+ ID_Name +" FROM "+TableName+" WHERE rowid="+ i.ToString(); i = cmd.ExecuteScalar();
回答4:
The SQLiteConnection object has a property for that, so there is not need for additional query. After INSERT you just my use LastInsertRowId property of your SQLiteConnection object that was used for INSERT command. Type of LastInsertRowId property is Int64. Off course, as you already now, for auto increment to work the primary key on table must be set to be AUTOINCREMENT field, which is another topic.