python – 处理psycopg2中的错误 psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, comm

it2025-02-15  5

问题

import psycopg2 # 数据库连接参数 conn = psycopg2.connect(database="xxx", user="xx", password="xxx", host="192.168.1.2", port="5432") cur = conn.cursor() cur.execute("SELECT * FROM test;") rows = cur.fetchall() # all rows in table print(rows) for i in rows: print(i) conn.commit() cur.close() conn.close()

通过psycopg2,调用数据的时候报错psycopg2.errors.InFailedSqlTransaction: current transaction is aborted, comm

 

原因

暂不明确

 

解决方案

改为下面的代码就正常访问到了数据库信息

import psycopg2 try: connection = psycopg2.connect(user="xxx", password="xx@#29", host="127.0.0.1", port="5432", database="xxx") cursor = connection.cursor() postgreSQL_select_Query = "select * from xxx" cursor.execute(postgreSQL_select_Query) mobile_records = cursor.fetchall() for row in mobile_records: print("Id = ", row[0], ) print("Model = ", row[1]) print("Price = ", row[2], "\n") except (Exception, psycopg2.Error) as error : print ("Error while fetching data from PostgreSQL", error) finally: #closing database connection. if(connection): cursor.close() connection.close() print("PostgreSQL connection is closed")

 

最新回复(0)