[英]Unable to connect to database error when implementing try / except statement in python
我下面有一个python脚本,试图建立与sql db的连接。 数据库出现了一些问题,我希望脚本尝试重新连接到数据库,因此我添加了try / except。 但是现在我收到错误消息“无法连接到数据库”。 如果我删除try / except语句,脚本将完美运行。 如果有人可以帮助我使try / except语句正常工作,我将不胜感激!
在Try内使用连接更新了代码
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:
unique_domains = ''
while True:
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)$
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))
break
except:
pass
#print("\n\033[1;31m[!] Unable to connect to the database\n\033[1;m")
if __name__ == "__main__":
connect_to_db()
您需要做一些事情:
移动此代码:
conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST))
cursor = conn.cursor()
进入try
,以这种方式在死时循环时会重新建立连接。 像这样:
try:
conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST))
cursor = conn.cursor()
for cnt, domain_name in enumerate(fp):
print("Line {}: {}".format(cnt, domain_name))
print(domain_name)
domain_name = domain_name.rstrip()
我会在连接之间停顿一下。 您的DBA可能具有在一段时间内检测到太多连接的代码,如下所示:
#at the top of your code
import time
#in your loop add:
time.sleep(1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.