Python使用pymysql连接Mysql数据库操作笔记:连接、游标与 execute、executemany——含手动管理与 with 自动管理两种写法

conn.commit():提交事务,使修改操作永久生效

cursor.close():关闭游标,释放游标资源(推荐但不强制)

conn.close():关闭连接,释放数据库连接资源(必须)

cursor.execute():执行单条SQL语句,适用于一次操作一条记录。

cursor.executemany():批量执行同一条SQL语句,适用于一次操作多条记录。

1、查询语句的话 cursor.execute和 cursor.executemany没有区别

2、cursor.fetchone()表示返回查询结果中的1行,cursor.fetchmany(3)表示返回查询结果中的3行,cursor.fetchall()表示返回所有查询结果

传统方式(需要手动管理,即需要conn.commit()和cursor.close()和conn.close()):

python 复制代码
import pymysql
conn = None
cursor = None
try:
    # 1. 建立连接
    conn = pymysql.connect(host='localhost', user='root', password='PassWord', database='test')
    
    # 2. 创建游标
    cursor = conn.cursor()
    
    # 3. 执行查询
    cursor.execute("SELECT * FROM users WHERE age > %s", (20,))
    results = cursor.fetchall()
    
    # 4. 执行修改(需要提交)
    cursor.execute("UPDATE users SET status = 'active' WHERE age > %s", (20,))
    
    # 5. 提交事务
    conn.commit()
    
except Exception as e:
    # 6. 出错时回滚
    if conn:
        conn.rollback()
    print(f"错误: {e}")
    
finally:
    # 7. 关闭游标(如果存在)
    if cursor:
        cursor.close()
    
    # 8. 关闭连接(如果存在)
    if conn:
        conn.close()

使用with语句(自动管理):

备注:用with Connection(...)的则需要先from pymysql import Connection,实际上with pymysql.connect(...) 和 with Connection(...) 等价,因为 connect() 返回的就是 Connection 对象

python 复制代码
import pymysql

try:
    # 使用with自动管理连接和游标
    with pymysql.connect(host='localhost', user='root', password='PassWord', database='test') as conn:
        with conn.cursor() as cursor:
            # 执行查询
            cursor.execute("SELECT * FROM users")
            results = cursor.fetchall()
            
            # 执行修改
            cursor.execute("UPDATE users SET last_login = NOW()")
            
        # 连接上下文结束时自动提交(如果没出错)或回滚(如果出错)
        
except Exception as e:
    print(f"错误: {e}")

cursor.executemany()示例

python 复制代码
import pymysql

conn = pymysql.connect(host='localhost', user='root', password='PassWord',database='db1')
cursor = conn.cursor()

# 批量插入多条记录
users_data = [
    ('Bob', 30, 'bob@example.com'),
    ('Charlie', 35, 'charlie@example.com'),
    ('David', 28, 'david@example.com')
]

cursor.executemany(
    "INSERT INTO table1 (name, age, email) VALUES (%s, %s, %s)",
    users_data
)
#table1是空表,插入了3条记录

# 批量更新多条记录
update_data = [
    (26, 'Alice'),
    (31, 'Bob'),
    (36, 'Charlie')
]

cursor.executemany(
    "UPDATE table1 SET age = %s WHERE name = %s",
    update_data
)
#update语句中只更新了31, 'Bob'和36, 'Charlie'这两行,没有更新26, 'Alice'是因为name='Alice'的行不存在
conn.commit()

cursor.execute()示例

python 复制代码
import pymysql

conn = pymysql.connect(host='localhost', user='root', password='PassWord',database='db1')
cursor = conn.cursor()


# 插入单条记录
cursor.execute(
    "INSERT INTO table1 (name, age, email) VALUES (%s, %s, %s)",
    ('Alice', 25, 'alice@example.com')
)

# 查询单条记录
cursor.execute("SELECT * FROM table1 WHERE age = %s", (25,))
result = cursor.fetchone()
print(result)

# 更新单条记录
cursor.execute(
    "UPDATE table1 SET age = %s WHERE name = %s",
    (26, 'Alice')
)

conn.commit()

备注:以上insert和update中cursor.execute改成cursor.executemany都会报错TypeError: not enough arguments for format string,但是SELECT中cursor.execute改成cursor.executemany没有问题

相关推荐
SEO_juper2 天前
Node.js Product 结构化数据生成器:给产品页一键生成 JSON-LD
开发语言·前端·javascript·人工智能·node.js·json·1024程序员节
Android系统攻城狮5 天前
FFmpeg深度解析之av_codec_iterate:如何遍历音视频编解码器?(七十八)
linux·运维·ffmpeg·音视频·1024程序员节·音视频进阶
晚霞的不甘9 天前
Flutter/OpenHarmony 三方库适配实战:google_maps_flutter 地图
flutter·macos·华为·cocoa·harmonyos·1024程序员节
开开心心就好15 天前
显示器关不掉怎么办,用小工具一键息屏
算法·智能手机·pdf·计算机外设·ocr·lua·1024程序员节
Evand J15 天前
【MATLAB例程】基于IMM-EKF与AOA/测距融合的二维移动目标跟踪定位
matlab·代码·定位·1024程序员节·toa·aoa
普通人619 天前
PHP多维数组排序完全指南
开发语言·php·1024程序员节
普通人621 天前
WebGL与WebGPU入门指南
开发语言·webgl·1024程序员节
猫猫不是喵喵.22 天前
从0到1创建一个微服务项目
java·数据库·微服务·1024程序员节
fish_zzzz25 天前
笔记-论数据结构2
1024程序员节
普通人61 个月前
PHP文件读写完全指南
开发语言·php·1024程序员节