Python: 为与 mysql 的拒绝数据库连接创建异常

Python: Create an exception for a refused database conection with pymysql

今天我遇到了当编程脚本 运行 时数据库宕机的问题。我想在再次发生这种情况时创建一个例外,以便向我发送电子邮件(我已经创建了执行此操作的功能)。但是我试图为它创建一个例外失败了。

   import pymysql.cursors

    #Conection Settings....

    try:

       with connection.cursor() as cursor:
             # Read a single record
            sql =   "select  count(*) as total_invoices, " \
                    "sum(e.Montant_vente - e.Montant_tva_recup) as total_amount " \
                    "from  extrait_sapeig_stat e " \
                    "where e.montant_vente != 0 " \
                    "and e.numero_client = 1086 " \
                    "and e.activite != 11 " \
                    "and e.invoice_date = date_add(curdate(), Interval -1 DAY) " \
                    "and right(e.Numero_facture,7) not in (1182499)  " \


            print(sql)
            cursor.execute(sql)
            inv_counts_2 = cursor.fetchall()


    finally:
        connection.close()

因为你没有定义异常。

   import pymysql.cursors

    #Connection Settings....

    try:

       with connection.cursor() as cursor:
             # Read a single record
            sql =   "select  count(*) as total_invoices, " \
                    "sum(e.Montant_vente - e.Montant_tva_recup) as total_amount " \
                    "from  extrait_sapeig_stat e " \
                    "where e.montant_vente != 0 " \
                    "and e.numero_client = 1086 " \
                    "and e.activite != 11 " \
                    "and e.invoice_date = date_add(curdate(), Interval -1 DAY) " \
                    "and right(e.Numero_facture,7) not in (1182499)  " \


            print(sql)
            cursor.execute(sql)
            inv_counts_2 = cursor.fetchall()
    except Exception as e:
        print (e)

    finally:
        connection.close()