V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
milkpuff
V2EX  ›  数据库

Python 调用 mysql 能否一次执行多条语句

  •  
  •   milkpuff · 2022-12-08 11:57:59 +08:00 · 1022 次点击
    这是一个创建于 498 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现有一文件,其中存储大量 sql 语句,操作多个表,需要 python 读取并执行。

    使用 mysqlclient 库,似乎只能一次执行一条语句,执行 100 条语句需要 100 次网络通信;

    如果将语句用分号连接,调用 cursor.execute 会报:

    MySQLdb._exceptions.ProgrammingError: (2014, "Commands out of sync; you can't run this command now")
    

    cursor.executemany 方法只能对同一个表进行插入,不适用多表的情形。并且查看 executemany 的源码发现也是逐条请求的。

    请问,一次网络请求执行多条 sql 语句,能否实现?

    第 1 条附言  ·  2022-12-12 22:38:28 +08:00

    已解决 #1 楼所说的参数multi=True 参数是mysql-connector库中的用法,mysqlclient库没有这个参数。 mysqlclient中使用如下用法:

    sql = 'select * from table1; select * from table2;'
    cursor.execute(sql)
    while cursor.nextset():  # 关键: 没有此步commit会报语法错误
        pass
    db.commit()
    
    2 条回复    2022-12-08 12:07:42 +08:00
    westoy
        1
    westoy  
       2022-12-08 12:02:32 +08:00   ❤️ 1
    execute 加个 multi=True 试试
    sarices
        2
    sarices  
       2022-12-08 12:07:42 +08:00
    `
    # read the file containing the SQL statements
    with open('sql_statements.txt', 'r') as f:
    sql = f.read()

    # create a cursor and execute the SQL statements
    cursor = conn.cursor()
    cursor.executescript(sql)

    `
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   901 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:05 · PVG 06:05 · LAX 15:05 · JFK 18:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.