Python:使用pymysql为拒绝的数据库连接创建一个例外

时间:2016-09-23 09:19:13

标签: python mysql pymysql try-except

今天,当编程脚本运行时,我遇到了数据库问题。我想再次发生这种情况时给我发一封电子邮件(我已经创建了这个功能)。但是我没有尝试为它创建一个例外。

   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()

1 个答案:

答案 0 :(得分:0)

因为您尚未定义例外。

   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()