更新数据 (UPDATE)完整代码如下:
from contextlib import contextmanager
import mysql.connector
from mysql.connector import Error
class DatabaseConfig:
"""数据库配置类,集中管理连接参数"""
HOST = '192.168.116.70' # 数据库服务器地址
PORT = 3306 # 数据库端口号
DATABASE = 'python_mysql_demo' # 数据库名
USER = 'root' # 数据库用户名
PASSWORD = 'aaaaaa' # 数据库密码
CHARSET = 'utf8mb4' # 字符集,该字符集可支持emoji表情
class Database:
"""数据库操作封装"""
def __init__(self, config=DatabaseConfig):
self.config = config
self.connection = None
def connect(self):
"""建立连接"""
self.connection = mysql.connector.connect(
host=self.config.HOST,
port=self.config.PORT,
database=self.config.DATABASE,
user=self.config.USER,
password=self.config.PASSWORD,
charset=self.config.CHARSET,
autocommit=False
)
return self.connection
def close(self):
"""关闭连接"""
if self.connection and self.connection.is_connected():
self.connection.close()
def __enter__(self):
"""
进入上下文管理器,建立数据库连接
在 with 语句入口处被调用,建立连接并返回实例本身
"""
self.connect()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""
退出上下文管理器,关闭数据库连接
"""
self.close()
def update_student_email(db, student_id, new_email):
"""更新学生邮箱"""
sql = "UPDATE students SET email = %s WHERE id = %s"
cursor = db.connection.cursor()
cursor.execute(sql, (new_email, student_id))
db.connection.commit()
return cursor.rowcount # 返回受影响行数
def increment_age(db, student_id):
"""原子递增年龄,避免并发问题"""
sql = "UPDATE students SET age = age + 1 WHERE id = %s"
cursor = db.connection.cursor()
cursor.execute(sql, (student_id,))
db.connection.commit()
return cursor.rowcount
if __name__ == "__main__":
# 使用上下文管理器进行数据库操作
with Database() as db:
# 更新学生邮箱
rows_updated = update_student_email(db, student_id=23, new_email="newemail@example.com")
print(f"更新了 {rows_updated} 行学生的邮箱")
# 原子递增年龄
rows_incremented = increment_age(db, student_id=23)
print(f"增加了 {rows_incremented} 行学生的年龄")