mysqlconnector python错误:“命令不同步;您现在不能运行此命令”

时间:2019-12-03 04:00:21

标签: python mysql mysql-connector

我正在研究一个Python项目,其中我使用定义的过程和功能等多次查询数据库。但是,似乎我只能从一条准备好的语句中得到结果,然后再出现错误。

代码如下:

    db = mysql.connector.connect(host="localhost", user="root", passwd="root", database="srd")
    cursor = db.cursor()

 # Column names
    cursor.execute("CALL show_columns(\"race\")")
    labels = cursor.fetchall()

# concat it into one line
    build = ""
    for labels in labels:
        build = build + labels[0] + " | "
    print(build)

# content
    cursor.execute("CALL select_all(\"race\")")
    results2 = cursor.fetchall()
    for result in results2:
        print(result)
    cursor.close()

这是输出:

race_name | strengthASI | dexterityASI | constitutionASI | wisdomASI | intelligenceASI | charismaASI | flex_points | size | speed | abilities | proficiencies | has_subrace | 
// This part is correct output for printing the columns (the first query)


 File "C:\Python36\lib\site-packages\mysql\connector\connection_cext.py", line 472, in cmd_query
    raw_as_string=raw_as_string)
_mysql_connector.MySQLInterfaceError: Commands out of sync; you can't run this command now


mysql.connector.errors.DatabaseError: 2014 (HY000): Commands out of sync; you can't run this command now

1 个答案:

答案 0 :(得分:0)

在阅读了文档之后,我使用cursor.execute("CALL ...")调用过程是错误的。

正确的方法是使用cursor.callproc()方法,然后通过cursor.stored_results检索数据。