在 sqflite 中使多个操作原子化

发布于 2025-01-17 20:27:12 字数 141 浏览 0 评论 0原文

我正在扑动中创建一个移动应用程序,需要在交易表中进行条目,还需要更新用户表中的余额。每当要添加新事务时,我都会首先检查用户的当前余额,在交易表中添加条目并更新余额。我的问题是如何使整个Atomic进行整个操作。假设更新余额失败,因为出于任何原因,我还能从交易表中退回。

I am creating a mobile application in flutter where I need to do entries in the transaction table and also need to update the balance in the user table. Whenever a new transaction is to be added I first check the current balance of the user, add the entry in the transaction table and update the balance. My question is how can I make the entire operation atomic. Say if the update balance fails because for any reason how can I roll back from the transaction table also.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

伴随着你 2025-01-24 20:27:12

这正是 SQLite 事务 的用途! (很抱歉您的表名称不幸,也称为事务)有关

如何在 sqflite 中使用事务的更多信息,请参见:

https://github.com/tekartik/sqflite/blob/master/sqflite/doc/sql.md#transaction

为了方便起见,复制/粘贴了一些信息:

事务

transaction 句柄“全有或全无”的场景。如果一个命令失败(并引发错误),则所有其他命令都会恢复。

await db.transaction((txn) async {
  await txn.insert('my_table', {'name': 'my_name'});
  await txn.delete('my_table', where: 'name = ?', whereArgs: ['cat']);
});
  • 确保内部事务对象 - 上面代码中的 txn - 在事务中使用(使用 db 对象本身会导致死锁),
  • 您可以抛出事务期间发生错误以取消事务,
  • 当事务期间抛出错误时,操作将立即取消,并且事务中之前的命令将被恢复,
  • 期间不能对数据库进行其他并发修改(即使是来自外部进程)一个事务,
  • 事务的内部部分只被调用一次,由开发人员来处理重试循环 - 假设它在某个时候可以成功。

That is exactly what SQLite transactions are for! (Sorry for the unfortunate name of your table which is also called transaction)

More info on how to use transactions in sqflite here:

https://github.com/tekartik/sqflite/blob/master/sqflite/doc/sql.md#transaction

some copy/pasted information for convenience:

transaction

transaction handle the 'all or nothing' scenario. If one command fails (and throws an error), all other commands are reverted.

await db.transaction((txn) async {
  await txn.insert('my_table', {'name': 'my_name'});
  await txn.delete('my_table', where: 'name = ?', whereArgs: ['cat']);
});
  • Make sure to sure the inner transaction object - txn in the code above - is used in a transaction (using the db object itself will cause a deadlock),
  • You can throw an error during a transaction to cancel a transaction,
  • When an error is thrown during a transaction, the action is cancelled right away and previous commands in the transaction are reverted,
  • No other concurrent modification on the database (even from an outside process) can happen during a transaction,
  • The inner part of the transaction is called only once, it is up to the developer to handle a try-again loop - assuming it can succeed at some point.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文