在INSERT上如何检索ROWID或AUTOINCREMENT值?

时间:2018-01-11 23:59:36

标签: c# sqlite system.data.sqlite

我正在使用SQLite编写INSERT,要么我正在使用AUTOINCREMENT,要么只使用ROWID作为主键。执行INSERT后,如何找到刚插入的行的主键是什么?

我知道如果我在Sql Server中工作该怎么办,但这是SQLite。

这是我的代码:

public bool AddPlanet(Planet p)
{
    bool result = false;
    SQLiteConnection sqlConnection;
    using (sqlConnection = new SQLiteConnection(ConnString))
    {
        sqlConnection.Open();
        sqlCommand = new SQLiteCommand(sqlConnection);
        sqlCommand.CommandText =
            String.Format(
                "insert into planet (name, satellites) values ('{0}',{1})"
                , p.Name
                , p.Satellites.ToString()
                );
        sqlCommand.CommandType = CommandType.Text;
        int x = sqlCommand.ExecuteNonQuery();
        // WHAT DO I DO HERE TO FIND OUT THE ROWID OF
        // THE ROW THAT WAS JUST INSERTED?
        if (x > 0) result = true;
        sqlConnection.Close();
    }
    return result;
}  

1 个答案:

答案 0 :(得分:0)

对于SQLite,您可以使用

SELECT last_insert_rowid()

这是另一个包含更多详细信息的stackoverflow帖子

How to retrieve the last autoincremented ID from a SQLite table?

相关问题