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

问题

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")

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值