SoFunction
Updated on 2025-04-08

How to get the self-growth ID of newly inserted data in SQLite database

Introduction to SQLite

This tutorial helps you understand what SQLite is, how it differs from SQL, why it is needed, and how it is processed by its application database.

SQLite is a software library that implements a self-sufficial, serverless, zero-configuration, transactional SQL database engine. SQLite is the fastest growing database engine, which is a growth in popularity, and has nothing to do with its size. SQLite source code is not subject to copyright restrictions.

What is SQLite?

SQLite is an in-process library that implements a self-sufficial, serverless, zero-configuration, transactional SQL database engine. It is a zero configuration database, which means unlike other databases, you don't need to configure it in your system.

Like other databases, the SQLite engine is not a standalone process that can be connected statically or dynamically according to application requirements. SQLite directly accesses its stored files.

There is a self-increment column in the SQLite database with a column named ID. The project requires that the ID of the newly inserted data row be returned to the database while inserting new data.

I use transactions here to submit the insertion and query statements together through ExecuteReader, and return the DbDataReader.

Next, we introduce how to obtain the self-growth ID of the newly inserted data in the SQLite database. The code is as follows:

Implement code

public bool Insert(string topic, string key, string value, out int id)
{
    DbProviderFactory factory = ;
    using (DbConnection conn = ())
    {
         = _connectionString;
        ();
        DbCommand cmdInsert = ();
        (());
        (());
        (());
        DbTransaction trans = ();
        try
        {
             = "INSERT INTO [{0}] ([Topic],[Key],[Value]) VALUES (?,?,?);SELECT LAST_INSERT_ROWID() FROM [{0}]";
             = (, _messageTableName);
            [0].Value = topic;
            [1].Value = key;
            [2].Value = value;
            DbDataReader reader = ();
            ();
            if (())
            {
                id = (reader[0].ToString());
                ();
                return true;
            }
            else
            {
                SAEC_Log4net.("insert message to db fail");
                id = 0;
                return false;
            }
        }
        catch (Exception e)
        {
            ();
            SAEC_Log4net.(());
            id = 0;
            return false;
        }
    }
}

This is the article about obtaining the self-growth ID of newly inserted data in SQLite database. For more related content on the self-growth ID of newly inserted SQLite data, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!