使用pgerror设置引发psycopg2 ProgrammingError的方法如下:
pip install psycopg2
import psycopg2
conn = psycopg2.connect(database="your_database", user="your_username", password="your_password", host="your_host", port="your_port")
cur = conn.cursor()
cur.execute("SET pgerror TO 'your_error_message'")
cur.execute("SELECT * FROM your_table")
except psycopg2.ProgrammingError as e:
完整的示例代码如下:
import psycopg2
try:
conn = psycopg2.connect(database="your_database", user="your_username", password="your_password", host="your_host", port="your_port")
cur = conn.cursor()
cur.execute("SET pgerror TO 'your_error_message'")
cur.execute("SELECT * FROM your_table")
except psycopg2.ProgrammingError as e:
print("Error:", e)
finally:
if cur:
cur.close()
if conn:
conn.close()
这样,当执行SQL查询或操作时,如果出现错误,将会引发psycopg2的ProgrammingError异常,并且异常信息中将包含你设置的错误信息。
领取专属 10元无门槛券
手把手带您无忧上云