Getting the Last Insert ID with SQLite.NET in C#

后端 未结 8 1293
执笔经年
执笔经年 2020-11-30 07:20

I have a simple problem with a not so simple solution... I am currently inserting some data into a database like this:

kompenzacijeDataSet.KompenzacijeRow kom         


        
8条回答
  •  抹茶落季
    2020-11-30 08:04

    I'm using Microsoft.Data.Sqlite package and I do not see a LastInsertRowId property. But you don't have to create a second trip to database to get the last id. Instead, combine both sql statements into a single string.

            string sql = "insert into MyTable values (null, @name);  select last_insert_rowid();";
            using (var cmd = conn.CreateCommand()) {
                cmd.CommandText = sql;
                cmd.Parameters.Add("@name", SqliteType.Text).Value = "John";
                int lastId = Convert.ToInt32(cmd.ExecuteScalar());
            }
    

提交回复
热议问题