Python:如何使用psycopg2将字符串传递给postgres命令

时间:2015-09-24 20:05:27

标签: python postgresql psycopg2

我在将一个字符串传递给python中的postgresql查询时遇到问题。特别是我有以下完美的脚本:

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()

但如果我使用变量test更改y,则会给我一个错误。

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'

2 个答案:

答案 0 :(得分:0)

您可以使用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()

答案 1 :(得分:0)

不幸的是,它不起作用,当我尝试将句子放在中间时,我遇到同样的问题,例如:

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