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

后端 未结 8 1266
执笔经年
执笔经年 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:12

    There seems to be answers to both Microsoft's reference and SQLite's reference and that is the reason some people are getting LastInsertRowId property to work and others aren't.

    Personally I don't use an PK as it's just an alias for the rowid column. Using the rowid is around twice as fast as one that you create. If I have a TEXT column for a PK I still use rowid and just make the text column unique. (for SQLite 3 only. You need your own for v1 & v2 as vacuum will alter rowid numbers)

    That said, the way to get the information from a record in the last insert is the code below. Since the function does a left join to itself I LIMIT it to 1 just for speed, even if you don't there will only be 1 record from the main SELECT statement.

    SELECT my_primary_key_column FROM my_table
    WHERE rowid in (SELECT last_insert_rowid() LIMIT 1);
    
    0 讨论(0)
  • 2020-11-30 08:16
    # How about just running 2x SQL statements together using Execute Scalar?
    # Person is a object that has an Id and Name property
    
    var connString = LoadConnectionString(); // get connection string
    using (var conn = new SQLiteConnection(connString)) // connect to sqlite
    {
    
        // insert new record and get Id of inserted record
        var sql = @"INSERT INTO People (Name) VALUES (@Name);
                    SELECT Id FROM People
                    ORDER BY Id DESC";
    
        var lastId = conn.ExecuteScalar(sql, person);
    }
    
    0 讨论(0)
提交回复
热议问题