MQ(消息队列)与MySQL事务
基础概念:
相关优势:
类型与应用场景:
应用场景:
遇到的问题及解决方法:
示例代码(以Python和MySQL为例):
import mysql.connector
from mysql.connector import Error
try:
# 连接MySQL数据库
connection = mysql.connector.connect(host='localhost',
database='test_db',
user='root',
password='password')
if connection.is_connected():
# 开始事务
cursor = connection.cursor()
cursor.execute("START TRANSACTION;")
# 执行SQL语句
sql_insert = "INSERT INTO employees (first_name, last_name, age) VALUES (%s, %s, %s)"
values = ('John', 'Doe', 30)
cursor.execute(sql_insert, values)
sql_update = "UPDATE employees SET age = %s WHERE first_name = %s"
new_age = 31
cursor.execute(sql_update, (new_age, 'John'))
# 提交事务
connection.commit()
print("Transaction committed successfully.")
except Error as e:
# 回滚事务
if connection.is_connected():
connection.rollback()
print(f"Transaction rolled back due to error: {e}")
finally:
# 关闭数据库连接
if connection.is_connected():
cursor.close()
connection.close()
参考链接地址:
领取专属 10元无门槛券
手把手带您无忧上云