如何使用SQLiteCommand对象获取自动插入的ID插入行

时间:2019-10-29 04:27:07

标签: c# sqlite

我有一个SQLite连接对象和一个命令对象。我使用ExecuteNonQuery函数在表中插入一行。如何从中获取自动增量列(ID)的值?

用于创建数据库的代码:

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

我在数据库中插入值的代码:


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;
    } 
}

此代码正确插入。但是在我试图获取ID的行中抛出了一个异常(System.ArgumentOutOfRangeException)。发生了什么/我该如何解决?

编辑1:在try块中,我添加了代码以运行另一个查询“从MyTable中选择max(ID)”:

    try
            {
                cmdObj.ExecuteNonQuery();

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

                Console.WriteLine(id);
            }

此代码引发相同的异常。

1 个答案:

答案 0 :(得分:1)

select last_insert_rowid();

您将需要将其作为标量查询执行。

string sql = @"select last_insert_rowid()";
long lastId = (long)command.ExecuteScalar(sql); // Need to type-cast since `ExecuteScalar` returns an object.