mysql中except语句出错_在python中实现try/except语句时无法连接到数据库错误

下面有一个python脚本,它试图连接到sqldb。数据库有一些问题,我希望脚本尝试重新连接到数据库,所以我添加了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()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值