下午好,我从python学习了使用postgresql的库,它写在描述中:
Never, never, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.
我想从 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
的情况下创建函数吗?
最佳答案
您应该有一个要传递的列名列表,而不是传递字符串列。现在您可以使用 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)
关于python-3.x - 查询数据库 postgreSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54160034/