【问题标题】:Check if query run successfully through python检查查询是否通过python成功运行
【发布时间】:2015-07-09 06:21:03
【问题描述】:

我有一个包含所有 mysql 查询的 .sql 脚本。现在假设在执行脚本后我想检查查询是否成功运行。如果我们这样做,在命令行中

echo $?

如果查询成功则返回0,不成功则返回1。

不,我想用 python 脚本来做。如何才能做到这一点 ?

我的python脚本:

import mysql.connector
from mysql.connector import errorcode

try:
    cnx = mysql.connector.connect(user='myuser', password='mypass', host='127.1.2.3', database='mydb')
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        print("Something is wrong with your user name or password")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("Database does not exist")
    else:
        print(err)
else:
    cursor = cnx.cursor()
    cursor.executescript("sql_queries.sql")
    cnx.close()

【问题讨论】:

    标签: python mysql bash


    【解决方案1】:

    您是说在运行脚本后让 python 返回退出代码吗?你想阅读sys.exit。

    在您的示例中,您可能会有类似

    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
        ...
        sys.exit(1)
    else:
        cursor = cnx.cursor()
        # Might want to check whether the executescript was successful
        try:
            cursor.executescript("sql_queries.sql")
        except mysql.connector.Error as err:
            print(err)
            sys.exit(1)
        cnx.close()
    

    当然,前段时间有人问过这个问题,还有其他相关问题:

    还请考虑将错误消息发送到 stderr,而不是将默认的 print() 留给 stdout,请参阅:

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多