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

刺骨的言语ヽ痛彻心扉 2022-12-17 04:26 352阅读 0赞

问题

  1. import psycopg2
  2. # 数据库连接参数
  3. conn = psycopg2.connect(database="xxx", user="xx", password="xxx", host="192.168.1.2", port="5432")
  4. cur = conn.cursor()
  5. cur.execute("SELECT * FROM test;")
  6. rows = cur.fetchall() # all rows in table
  7. print(rows)
  8. for i in rows:
  9. print(i)
  10. conn.commit()
  11. cur.close()
  12. conn.close()

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

原因

暂不明确

解决方案

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

  1. import psycopg2
  2. try:
  3. connection = psycopg2.connect(user="xxx",
  4. password="xx@#29",
  5. host="127.0.0.1",
  6. port="5432",
  7. database="xxx")
  8. cursor = connection.cursor()
  9. postgreSQL_select_Query = "select * from xxx"
  10. cursor.execute(postgreSQL_select_Query)
  11. mobile_records = cursor.fetchall()
  12. for row in mobile_records:
  13. print("Id = ", row[0], )
  14. print("Model = ", row[1])
  15. print("Price = ", row[2], "\n")
  16. except (Exception, psycopg2.Error) as error :
  17. print ("Error while fetching data from PostgreSQL", error)
  18. finally:
  19. #closing database connection.
  20. if(connection):
  21. cursor.close()
  22. connection.close()
  23. print("PostgreSQL connection is closed")

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FpbmdmZW5neGQx_size_16_color_FFFFFF_t_70

发表评论

表情:
评论列表 (有 0 条评论,352人围观)

还没有评论,来说两句吧...

相关阅读