解决Python对Postgres批量操作解决单值元组引发的报错
背景
Python对Postgres批量操作时,若传入的条件变量为单元素的元组时,会引发语法报错,原因是python中单值元组为(“xxx”,)而逗号在sql语句中将会被识别出错,故使用代码示例中方法三中的写法来解决此问题
代码示例
import psycopg2.extras
pg_conn = psycopg2.connect(database="postgres", user="postgres", password="xxxxx", host="10.255.xx.xxx", port="5432")
cursor = pg_conn.cursor()
# 方法一:当变量为多值时,不会引发报错
id_list = [66, 70]
cursor.execute(f"select id,name,data from table_test where id in {tuple(id_list)}")
result_1 = cursor.fetchall()
pg_conn.commit()
print(result_1)
# 方法一:当变量为单值时会引发报错
id_list = [66]
cursor.execute(f"select id,name,data from table_test where id in {tuple(id_list)}")
result_2 = cursor.fetchall()
pg_conn.commit()
print(result_2)
# 方法三:正确写法
id_list = [66]
sql = "select id,name,data from table_test where id in %(id_list)s"
values = {"id_list": tuple(id_list)}
cursor.execute(sql, values)
result_3 = cursor.fetchall()
pg_conn.commit()
print(result_3)
cursor.close()
pg_conn.close()