Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.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 psycopg2:光标已关闭_Python_Postgresql_Psycopg2 - Fatal编程技术网

Python psycopg2:光标已关闭

Python psycopg2:光标已关闭,python,postgresql,psycopg2,Python,Postgresql,Psycopg2,我使用的是psycopg2.6.1。我需要按顺序执行一系列查询 conn = psycopg2.connect(database=redshift_database, user=redshift_user, password=os.environ.get("PGPASSWORD"), host=redshift_cluster,

我使用的是
psycopg2.6.1
。我需要按顺序执行一系列查询

conn = psycopg2.connect(database=redshift_database,
                        user=redshift_user,
                        password=os.environ.get("PGPASSWORD"),
                        host=redshift_cluster,
                        port=redshift_port)
cursor = conn.cursor()

queries = [q1, q2, q3....] ## a list of queries 
for query in queries:
    try:
        cursor.execute(query)
    except:
        print e.message
假设
q1
SSL连接意外关闭而失败
。然后,当
光标已关闭时,我的其余查询也会失败。如何确保在一个查询失败的情况下成功执行以下查询

您应该在except(除外)区域中明确地重新生成光标,以防在查询的较低级别出现错误:

for query in queries:
    try:
        cursor.execute(query)
    except:
        print e.message
        try:
            cursor.close()
            cursor = conn.cursor()
        except:
            conn.close()
            conn = psycopg2.connect(...)
        cursor = conn.cursor()

假设连接已断开,则需要重新建立连接,并在异常处理程序中获取另一个游标:

for query in queries:
    try:
        cursor.execute(query)
    except Exception as e:
        print e.message
        conn = psycopg2.connect(....)
        cursor = conn.cursor()
对于捕捉到的异常,您应该更加具体。假设出现
InterfaceError
异常,如果光标以某种方式关闭,您可以像下面这样捕获:

except psycopg2.InterfaceError as e:
可能还有其他一些不太严重的问题会阻止后续查询的执行,例如事务被中止。在这种情况下,您需要回滚当前事务,然后尝试下一个查询:

queries = ['select count(*) from non_existent_table', 'select count(*) from existing_table']
for query in queries:
    try:
        cursor.execute(query)
    except psycopg2.ProgrammingError as exc:
        print exc.message
        conn.rollback()
    except psycopg2.InterfaceError as exc:
        print exc.message
        conn = psycopg2.connect(....)
        cursor = conn.cursor()
这里,对不存在的表尝试查询。引发了
ProgrammingError
异常,如果要尝试另一个查询,则必须回滚连接。第二个查询应该成功


这掩盖了异常处理程序本身引发的其他异常的细节,例如,
connect(…)
在尝试重新建立连接时可能会失败,因此,您也应该处理这个问题。

检查此链接可能对您有所帮助。连接关闭时正在进行的查询将抛出一个
操作错误
,随后的查询将抛出
接口错误
s