获取最后插入的 ID [英] Getting last inserted ID

查看:49
本文介绍了获取最后插入的 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用下面的方法来获取最后插入行的 ID.

 Database.ExecuteNonQuery(query, parameters);//如果此时另一个客户端/连接插入一条记录,//下面的行是否会返回错误的行 ID?int fileid = Convert.ToInt32(Database.Scalar("SELECT last_insert_rowid()"));返回文件ID;

到目前为止,这种方法运行良好,但我不确定它是否完全可靠.

假设有两个客户端应用程序,每个应用程序都有自己独立的数据库连接,它们同时调用上面的服务器端方法.请记住,客户端线程并行运行并且 SQLite 一次只能运行一个操作(或者我听说过),一个客户端实例是否有可能返回插入的记录的行 ID?另一个实例?

最后,有没有更好的方法来获取最后插入的行 ID?

解决方案

如果此时另一个客户端/连接插入一条记录,下面的行是否会返回错误的行 ID?

不,因为写入要么发生在读取之后,要么发生在读取之前,但不会发生在读取期间.

<块引用>

记住客户端线程并行运行并且 SQLite 一次只能运行一个操作,一个客户端是否有可能获得另一个客户端插入的记录的行 ID?

>

是的,当然.

在完全相同的时间调用服务器端方法并不重要.数据库的锁定允许并发读取,但不允许并发写入或边写边读.

如果您还没有阅读过SQLite 的文件锁定模型.>

I'm currently using the method below to get the ID of the last inserted row.

    Database.ExecuteNonQuery(query, parameters);

    //if another client/connection inserts a record at this time, 
    //could the line below return the incorrect row ID?
    int fileid = Convert.ToInt32(Database.Scalar("SELECT last_insert_rowid()"));
    return fileid;

This method has been working fine so far, but I'm not sure it's completely reliable.

Supposing there are two client applications, each with their own separate database connections, that invoke the server-side method above at exactly the same time. Keeping in mind that the client threads run in parallel and that SQLite can only run one operation at a time (or so I've heard), would it be possible for one client instance to return the row ID of a record that was inserted by the other instance?

Lastly, is there a better way of getting the last inserted row ID?

解决方案

If another client/connection inserts a record at this time, could the line below return the incorrect row ID?

No, since the write will either happen after the read, or before the read, but not during the read.

Keeping in mind that the client threads run in parallel and that SQLite can only run one operation at a time, would it be possible for one client to get the row ID of the record that was inserted by the other client?

Yes, of course.

It doesn't matter that the server-side methods are invoked at exactly the same time. The database's locking allows concurrent reads, though not concurrent writes, or reads while writing.

if you haven't already, have a read over SQLite's file locking model.

这篇关于获取最后插入的 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆