Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中实现try/except语句时出现无法连接到数据库错误_Python_Sql_Json_Python 3.x_Postgresql - Fatal编程技术网

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

在python中实现try/except语句时出现无法连接到数据库错误,python,sql,json,python-3.x,postgresql,Python,Sql,Json,Python 3.x,Postgresql,下面我有一个python脚本,它试图连接到sql数据库。数据库出现一些问题,我希望脚本尝试重新连接到数据库,因此我添加了try/except。但现在我收到了错误消息“无法连接到数据库”。如果我去掉try/except语句,脚本工作得非常好。如果有人能帮助我使try/except语句生效,我将不胜感激 更新了代码,并在Try内部建立了连接 from __future__ import print_function try: import psycopg2 except ImportErr

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

除了:
单独使用是非常糟糕的做法。例外可以是任何东西。将
Exception:
替换为
Exception作为e:
并将异常更改
Exception:
打印为
Exception作为错误:
,然后在下一行
print(str(error))
并查看它爆炸的原因。@Jean-Françoisfab感谢您的回复!我用“Exception as e:”替换了Exception,我打印了这个异常,下面是我得到的结果“你知道如何修复这个问题吗?我将非常感谢你的帮助@sniperd我发现了我的错误,不是我让我的脚本一直工作到149个查询,然后进程被终止。如何使进程即使在sql db被终止后仍能继续重新连接到它。您可能希望插入
sleep
命令,以便它在每个连接之间暂停几秒钟。DBA的代码可能会杀死任何似乎正在冲击数据库的东西。感谢您的帮助!我确实添加了睡眠延迟,不幸的是,我得到了同样的错误。我将连接代码移到try正下方的两行,仍然导致相同的错误。这是正确的地方吗?谢谢你的回复!我尝试了try语句的更新代码,但仍然得到相同的错误。您知道如何解决此问题吗?再次感谢您的帮助!关于如何解决此问题,您有什么建议吗?将连接移动到
try
块后,是否可以更新问题中的代码?也许我会看到一些东西谢谢你的回应!我更新了问题区中的代码。如果您能提供任何帮助,我将不胜感激!