尝试/ except语句导致SQL查询无法正常运行

时间:2018-08-03 19:49:23

标签: python sql python-3.x try-except

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

错误消息 追溯(最近一次通话):   在第63行的文件“ 2:38 pm”中     connect_to_db()   connect_to_db中的文件“ 2:38 pm”,第55行     pprint.pprint(unique_domains) 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()

1 个答案:

答案 0 :(得分:0)

看起来像在第55行上调用了try中定义的try。因此,如果pprint失败了,您将无法将其移到unique_domains之外。

您可以做的只是在您的try之前定义'',您可以将其设置为Nonetry只是取决于什么如果失败,您想使用它。那应该让您度过这个减速期,祝您好运! :)

如果您想重试数据库连接,则可以将except webpackCompiler.hooks.done.tap('BuildStatsPlugin', (stats) => { .... }); 逻辑循环定义的次数。