简体   繁体   中英

Python: how to pass string to postgres command using psycopg2

I have a problem passing a string to a query in python for postgresql. In particular I have the following script that works perfectly:

y = 'test'
for i in un:
    crs = conn.cursor()
    query = """
        select * 
        FROM  test
        WHERE test.vin_id = %s
    ;"""
    s_id = i
    crs.execute(query,[s_id])
    s_out = crs.fetchall()

but if I change test with the variable y it gives me an error.

for i in un:
    crs = conn.cursor()
    query = """
        select * 
        FROM  %s
        WHERE %s.vin_id = %s
    ;"""
    s_id = i
    crs.execute(query,[y,y,s_id])
    s_out = crs.fetchall()

ProgrammingError: syntax error at or near "'test'"
LINE 3:         FROM  'test'

You can use AsIs :

from psycopg2.extensions import AsIs
for i in un:
    crs = conn.cursor()
    query = """
        select * 
        FROM  %s
        WHERE %s.vin_id = %s
    ;"""
    s_id = i
    crs.execute(query,[AsIs(y),AsIs(y),s_id])
    s_out = crs.fetchall()

Unfortunately it does not work and I have the same problem when I try to put sentences in the middle, for instance:

query1 = """
SELECT * 
FROM test1 
WHERE %s LIKE '%'  || vin_id || '%' 
;"""    
crs1 = conn.cursor()
crs1.execute(query1, [s_id])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM