0

I have a SQLite Connection Object and a command object. I insert a row in my table using the ExecuteNonQuery function. How do I get the value of the autoincrement column (ID) from this?

Code for creating database:

creationQuery = "CREATE TABLE IF NOT EXISTS MyTable ( ID INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT ,MyCol1 NVARCHAR, MyCol2 NVARCHAR)";

My code for inserting values in the DB:


public void InsertIntoDB(string[] vals){

    // Global connection objects (This is in an API so every time a new instance of these are created)
    connObj = CreateConnection();
    cmdObj = connObj.CreateCommand();

    cmdObj.CommandText = "INSERT INTO MyTable ('MyCol1',MyCol2) VALUES( '" + vals[0] + "','" + vals[1] + "')";

    int id = -1;
    try{

        cmdObj.ExecuteNonQuery(); 
        id = (int)cmdObj.Parameters["id"].Value; // tried "@id" as well


    }catch(Exception ex){
        throw ex;
    } 
}

This code is inserting correctly. But throws an exception ( System.ArgumentOutOfRangeException) in the line where I'm trying to get the ID. Whats going on/ How do i solve this?

EDIT 1: Inside the try block, I added code to just run another query "Select max(ID) from MyTable":

    try
            {
                cmdObj.ExecuteNonQuery();

                cmdObj.CommandText = "Select Max(id) from MyTable";
                SQLiteDataReader myReader = cmdObj.ExecuteReader();
                while (myReader.Read())
                {
                    id = (int)myReader["id"];
                }

                Console.WriteLine(id);
            }

This code throws the same Exception.

1 Answers1

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.
Jimmy
  • 864
  • 13
  • 24