使用sqlite数据库的事务操作,编写一段模拟银行转账的逻辑代码
时间: 2023-10-31 18:03:09 浏览: 203
模拟银行转账
下面是一段使用SQLite数据库的事务操作代码来模拟银行转账的逻辑:
```python
import sqlite3
def transfer_funds(sender_account, receiver_account, amount):
# 连接到SQLite数据库
conn = sqlite3.connect('bank.db')
try:
# 开始事务
conn.execute('BEGIN TRANSACTION')
# 查询发送者账户余额
sender_balance = conn.execute('SELECT balance FROM accounts WHERE account_number=?', (sender_account,)).fetchone()[0]
# 查询接收者账户余额
receiver_balance = conn.execute('SELECT balance FROM accounts WHERE account_number=?', (receiver_account,)).fetchone()[0]
# 检查发送者账户余额是否足够
if sender_balance >= amount:
# 更新发送者账户余额
sender_new_balance = sender_balance - amount
conn.execute('UPDATE accounts SET balance=? WHERE account_number=?', (sender_new_balance, sender_account))
# 更新接收者账户余额
receiver_new_balance = receiver_balance + amount
conn.execute('UPDATE accounts SET balance=? WHERE account_number=?', (receiver_new_balance, receiver_account))
# 提交事务
conn.commit()
print('转账成功!')
else:
# 余额不足,事务回滚
conn.rollback()
print('转账失败:发送者账户余额不足!')
except Exception as e:
# 出现异常,事务回滚
conn.rollback()
print('转账失败:发生未知错误!', str(e))
finally:
# 关闭数据库连接
conn.close()
# 测试转账
transfer_funds('1234567890', '0987654321', 1000)
```
上述代码首先连接到了SQLite数据库,然后使用事务操作来扣除发送者账户余额并增加接收者账户余额。如果发送者账户余额足够,则更新两个账户的余额,并提交事务。如果发送者账户余额不足或发生了未知错误,则回滚事务。最后关闭数据库连接。
阅读全文