首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >无法连接到数据库错误,当在python中实现try / except语句时

无法连接到数据库错误,当在python中实现try / except语句时
EN

Stack Overflow用户
提问于 2018-08-06 20:29:49
回答 1查看 610关注 0票数 0

我下面有一个python脚本,它试图建立到sql数据库的连接。数据库有一些问题,我想让脚本尝试重新连接到数据库,所以我添加了try / except。然而,现在我收到错误消息"Unable to connect to database“。如果我去掉try / except语句,脚本就能很好地工作。如果有人能帮助我让try / except语句工作,我将不胜感激!

使用Try内部的连接更新了代码

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

发布于 2018-08-06 22:33:58

你需要做几件事:

移动此代码:

代码语言:javascript
复制
 conn = psycopg2.connect("dbname={0} user={1} host={2}".format(DB_NAME, DB_USER, DB_HOST)) 
 cursor = conn.cursor()

到你的try中,这样当它循环时,如果它死了,它将重新建立连接。如下所示:

代码语言:javascript
复制
    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可能需要在一段时间内检测太多连接,如下所示:

代码语言:javascript
复制
#at the top of your code
import time

#in your loop add:
time.sleep(1)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51707677

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档