下午好,我学习了用于使用python的postgresql的库,它是在描述中编写的:
永远不要使用Python字符串连接(+)或字符串参数内插(%)将变量传递给SQL查询字符串。即使在枪口下也不行。
我想从reports
表中输出列object, data
,我试图创建这样一个函数:
def select(self, column, table):
with conn.cursor() as cursor:
stmt = sql.SQL('SELECT {} FROM {}').format(
sql.Identifier(column),
sql.Identifier(table))
cursor.execute(stmt)
for row in cursor:
print(row)
但我发现了一个错误:
psycopg2.ProgrammingError: column "object, data" does not exist
LINE 1: SELECT "object, data" FROM "object"
我成功地使用以下函数实现了所需的结果:
def select(self, column, table):
with conn.cursor() as cursor:
cursor.execute("SELECT %s FROM %s" %(column,table))
return cursor.fetchall()
你能告诉我如何不用%s
来做一个函数吗?
发布于 2019-01-12 06:28:52
您不应该传递字符串列,而应该有要传递的列名的列表。现在您可以使用sql.SQL(', ').join()
加入它们。
def select(self, columns, table):
with conn.cursor() as cursor:
stmt = sql.SQL('SELECT {} FROM {}').format(
sql.SQL(', ').join(sql.Identifier(n) for n in columns),
sql.Identifier(table))
cursor.execute(stmt)
for row in cursor:
print(row)
https://stackoverflow.com/questions/54160034
复制