Python Try/except语句导致sql查询无法正常运行

Python Try/except语句导致sql查询无法正常运行,python,sql,python-3.x,try-except,Python,Sql,Python 3.x,Try Except,我有一个python脚本,可以从数据库中提取sql查询,但不幸的是,数据库存在性能问题,有时会杀死我的脚本。我的脚本在.txt文件中循环,以获取sql查询中使用的域名。我想在我的脚本中实现try和except,这样即使与数据库的连接暂时丢失,它也会自动继续重试。下面是我的代码和错误信息,非常感谢您的帮助 错误消息 回溯(最近一次呼叫最后一次): 文件“2:38pm”,第63行,在 将_连接到_db() 文件“2:38pm”,第55行,连接到数据库 pprint.pprint(唯一的\u域) Un

我有一个python脚本,可以从数据库中提取sql查询,但不幸的是,数据库存在性能问题,有时会杀死我的脚本。我的脚本在.txt文件中循环,以获取sql查询中使用的域名。我想在我的脚本中实现try和except,这样即使与数据库的连接暂时丢失,它也会自动继续重试。下面是我的代码和错误信息,非常感谢您的帮助

错误消息 回溯(最近一次呼叫最后一次): 文件“2:38pm”,第63行,在 将_连接到_db() 文件“2:38pm”,第55行,连接到数据库 pprint.pprint(唯一的\u域) UnboundLocalError:赋值前引用的局部变量“unique_domains”

代码

from __future__ import print_function

try:
    import psycopg2
except ImportError:
    raise ImportError('\n\033[33mpsycopg2 library missing. pip install psycopg2\033[1;m\n')
    sys.exit(1)

import re
import sys
import json
import pprint

outfilepath = "crtsh_output/crtsh_flat_file"

DB_HOST = 'crt.sh'
DB_NAME = 'certwatch'
DB_USER = 'guest'

conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST))
cursor = conn.cursor()

def connect_to_db():
    filepath = 'forager.txt'
    conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST))
    cursor = conn.cursor()
    with open(filepath) as fp:
        try:
            for cnt, domain_name in enumerate(fp):
                print("Line {}: {}".format(cnt, domain_name))
                print(domain_name)
                domain_name = domain_name.rstrip()


                cursor.execute('''SELECT c.id, x509_commonName(c.certificate), x509_issuerName(c.certificate), x509_notBefore(c.certificate), x509_notAfter(c.certificate), x509_issuerName(c.certificate), x509_k$
FROM certificate c, certificate_identity ci WHERE
c.id= ci.certificate_id AND ci.name_type = 'dNSName' AND lower(ci.name_value) =
lower(%s) AND x509_notAfter(c.certificate) > statement_timestamp()''',(domain_name,))


                unique_domains = cursor.fetchall()

                pprint.pprint(unique_domains)

                outfilepath = "crtsh1" + ".json"
                with open(outfilepath, 'a') as outfile:
                        outfile.write(json.dumps(unique_domains, sort_keys=True, indent=4, default=str, ensure_ascii = False))

        except:
            print("\n\033[1;31m[!] Unable to connect to the database\n\033[1;m")




        pprint.pprint(unique_domains)

        outfilepath = "crtsh1" + ".json"
        with open(outfilepath, 'a') as outfile:
                outfile.write(json.dumps(unique_domains, sort_keys=True, indent=4, default=str, ensure_ascii = False))


if __name__ == "__main__":
    connect_to_db()

在第55行,您可以调用
pprint.pprint(unique\u domains)
,这是在
try
中定义的。因此,如果
try
失败,您将无法在它之外使用
pprint

您可以这样做,它不会出错,只需定义
唯一的\u域
,在您的
尝试
之前,您可以将其设置为
'
,这取决于您在失败时想对其执行什么操作。这应该能让你通过减速带,祝你好运!:)


如果希望数据库连接重试,可以将
try
逻辑循环一定次数。

如果无法连接到数据库,则
唯一的\u域应该是什么?你为什么要阻止可能引发的错误?@PatrickHaugh unique_domains如果我无法连接到数据库,应该什么都不是。我并没有试图抑制我提出的错误。如何修复被抑制的错误?感谢您的回复!是否要保留唯一的\u domains=cursor.fetchall()在connect_to_db函数内部还是外部?我想我只需将
unique_domains='
直接放在你的
下面,打开
并在你的
上面尝试
至少可以帮你克服这个错误:)如果你发现我的答案有帮助,我会很感激你接受它:)祝你好运!谢谢你的帮助!我试过了,但还是会犯同样的错误。我应该把con和cursor放在哪里?