0

I tried to pass parameters the way it is described in the docs, but I get the following error: File "slug_word.py", line 100, in get_col cur.execute("select %s from %s" , data ) psycopg2.ProgrammingError: syntax error at or near "E'catalog_category'" LINE 1: select E'slug' from E'catalog_category'

Here are extracts from my code:

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)

2 Answers 2

2

By rereading a post Steve Holden about this issue I found the hint that in my code the parameters have to be passed the python way:

 ..."select %s from %s" % data ) 

Only 'real' data which goes into the database has to use the psycopg2 parameter method and not things like table and column names. Unfortunately mixing of data and table name does not work.

Sign up to request clarification or add additional context in comments.

Comments

1

You can use AsIs psycopg2 function:

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.