[英]psycopg2 pass arguments to SQL Programming Error
我试图按照文档中描述的方式传递参数 ,但出现以下错误:get_col cur.execute(“从%s中选择%s”,data)psycopg2.ProgrammingError:“ E'catalog_category”或附近的语法错误,文件“ slug_word.py”,第100行,第1行:从E'catalog_category'中选择E'slug'
这是我的代码的摘录:
def get_col(cxn, table, col):
"fetch a column"
cur = cxn.cursor()
data = (col, table)
cur.execute("select %s from %s" , data )
rows = cur.fetchall()
return rows
def main():
cxn = connect('galleria')
table = 'catalog_category'
col = 'slug'
rows = get_col(cxn, table, col)
通过重读有关此问题的文章Steve Holden ,我发现在我的代码中必须以python方式传递参数:
..."select %s from %s" % data )
只有进入数据库的“真实”数据才必须使用psycopg2参数方法,而不必使用表名和列名之类的东西。 不幸的是,数据和表名的混合不起作用。
您可以使用AsIs psycopg2函数:
适配器符合ISQLQuote协议,该协议对字符串表示形式已作为SQL表示形式有效的对象很有用。
import psycopg2
from psycopg2.extensions import AsIs
def get_col(conn, table, col):
'''Fetch a column'''
QUERY = 'SELECT %(col)s from %(table)s'
data = {'col': AsIs(col), 'table': AsIs(table)}
with conn.cursor() as cursor:
cursor.execute(QUERY, data)
rows = cursor.fetchall()
return rows
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.