python-3.x - 查询数据库 postgreSQL

标签 python-3.x postgresql psycopg2

下午好,我从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/

相关文章:

python - 如何从嵌套字典返回最大值及其关联键

database - 涉及 View 或带连接的选择的 PostgreSQL 行级安全性

mysql - 每种防止部分页面写入的方法有何优点?

django - 错误 : could not determine PostgreSQL version from '10.3' - Django on Heroku

python - 如何使用 Flask、SQLAlchemy 或 psycopg2 从 Postgres 中的游标获取数据

python - 将字典传递给 OrderedDict 有什么问题?

python - 如何仅在 python 中测试时启用内存分析器?

python-3.x - 定义以数字开头的函数名(在 Python 3 中)?

sql - 获取没有日期的最近季度

python - 如何从 psycopg2 导入 "connection"类?