psycopg2将参数传递给SQL编程错误

问题描述:

我试图按照文档中描述的方式传递参数,但出现以下错误: get_col中的文件“slug_word.py”,第100行012xxcur.execute( “来自%s选择%S”,数据) psycopg2.ProgrammingError:在语法错误或接近 “E'catalog_category'” LINE 1:选择E'slug“从E'catalog_category”psycopg2将参数传递给SQL编程错误

下面是我的提取代码:

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功能:从psycopg2.extensions

Adapter conform to the ISQLQuote protocol useful for objects whose string representation is already valid as SQL representation.

进口psycopg2 导入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