使用SQLite数据库的事务操作,编写一段模拟银行转账的逻辑代码
时间: 2023-05-11 09:03:15 浏览: 268
好的,以下是一段使用SQLite数据库的事务操作,模拟银行转账的逻辑代码:
```python
import sqlite3
def transfer_money(from_account, to_account, amount):
conn = sqlite3.connect('bank.db')
c = conn.cursor()
try:
# 开始事务
conn.execute('BEGIN TRANSACTION')
# 查询转出账户余额
c.execute('SELECT balance FROM accounts WHERE account_number = ?', (from_account,))
from_balance = c.fetchone()[0]
# 查询转入账户余额
c.execute('SELECT balance FROM accounts WHERE account_number = ?', (to_account,))
to_balance = c.fetchone()[0]
# 检查转出账户余额是否足够
if from_balance < amount:
raise ValueError('Insufficient balance')
# 更新转出账户余额
from_balance -= amount
c.execute('UPDATE accounts SET balance = ? WHERE account_number = ?', (from_balance, from_account))
# 更新转入账户余额
to_balance += amount
c.execute('UPDATE accounts SET balance = ? WHERE account_number = ?', (to_balance, to_account))
# 提交事务
conn.commit()
except Exception as e:
# 回滚事务
conn.rollback()
raise e
finally:
conn.close()
```
这段代码使用了 SQLite 数据库,实现了一个银行转账的逻辑。它首先查询转出账户和转入账户的余额,然后检查转出账户的余额是否足够,如果足够,就更新转出账户和转入账户的余额,并提交事务。如果出现任何异常,就回滚事务。
阅读全文