milkpuff
V2EX  ›  数据库

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

  •  
  •   milkpuff · Dec 8, 2022 · 1900 views
    This topic created in 1285 days ago, the information mentioned may be changed or developed.

    现有一文件,其中存储大量 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 语句,能否实现?

    Supplement 1  ·  Dec 12, 2022

    已解决 #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 replies    2022-12-08 12:07:42 +08:00
    westoy
        1
    westoy  
       Dec 8, 2022   ❤️ 1
    execute 加个 multi=True 试试
    sarices
        2
    sarices  
       Dec 8, 2022
    `
    # 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)

    `
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   980 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 34ms · UTC 19:31 · PVG 03:31 · LAX 12:31 · JFK 15:31
    ♥ Do have faith in what you're doing.