【问题标题】:python mysql connector multi=true Continue even if an SQL error occurspython mysql connector multi=true 即使出现SQL错误也继续
【发布时间】:2020-09-21 20:53:05
【问题描述】:

我正在使用 mysql 连接器 python 连接到 mysql 并通过设置 multi=True 运行多个查询。我得到了结果。如果任何语句中存在 sql 错误,则忽略错误之后的查询。即使发生 SQL 错误,如何使用“--force”并继续

conn = MYSQL.MySQLConnection(user=sql_username,password=sql_password,host='127.0.0.1',database=sql_main_database,port=3306)
cursor = conn.cursor(buffered=True)
try:
    results=cursor.execute("select now();SELECT UNIX_TIMESTAMP(now());select 'test';SELECT UTC_TIMESTAMP();select 'aravinth';select yuu;show processlist;select 1",multi=True)
except Exception as e:
    print(e)

count = 1

for result in results:
    if result.with_rows:

        print("Rows produced by statement '{}':".format(
        result.statement))
        print(result.fetchall())

    else:
         print("Number of rows affected by statement '{}': {}".format(
         result.statement, result.rowcount))

except Exception as e:
    print(e)

我的输出是

Rows produced by statement 'select now()':
[(datetime.datetime(2020, 6, 3, 13, 4, 54),)]
Rows produced by statement 'SELECT UNIX_TIMESTAMP(now())':
[(1591169694,)]
Rows produced by statement 'select 'test'':
[('test',)]
Rows produced by statement 'SELECT UTC_TIMESTAMP()':
[(datetime.datetime(2020, 6, 3, 7, 34, 54),)]
Rows produced by statement 'select 'aravinth'':
[('aravinth',)]
1054 (42S22): Unknown column 'yuu' in 'field list'
end

即使任何中间查询失败,我也想继续执行所有查询。

【问题讨论】:

    标签: python mysql python-3.x


    【解决方案1】:

    由于其中一个中间查询引发了Exception,因此您不能强制try 块从该点继续执行。你可以做的是:

    1. 声明results = []
    2. 在其自己的 try-catch 块中单独运行每个查询。
    3. 将每个查询的结果附加到results
    4. 以后使用results

    示例代码可以是:

    # assume that queries is a list containing all queries
    results = []
    for query in queries:
        try:
            result = cursor.execute(query)
            results.append(result)
        except Exception as e:
            print(e)
    
    for result in results:
        if result.with_rows:
    
            print("Rows produced by statement '{}':".format(
            result.statement))
            print(result.fetchall())
    

    【讨论】:

    • 我想一次性执行所有查询
    • 你看到cursor.execute(, multi=True)的代码了吗?我猜内部必须使用字符串解析器来生成查询,然后在每个查询之上运行cursor.execute()。由于您将所有这些批处理到一个 try-catch 块中,因此其中任何一个抛出异常都将导致 try 终止并随后执行语句。
    猜你喜欢
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 2021-01-10
    • 2022-11-02
    • 2021-09-21
    • 2021-12-22
    相关资源
    最近更新 更多