如何在 psycopg2 选择查询中使用字符串变量?

use*_*185 3 python psycopg2

从 PostgreSQL 列“u62194”获取数据时出错不存在

sql = """select userid from myusers WHERE userid='u62194' """ Of
course the hardcoded value works as it should.

import psycopg2

def select_tables():
    someuserid = 'u62194'
    print(someuserid)
    """ Run a select using a variable that is a string """
    sql = """select userid from myusers WHERE userid=%s """ %someuserid
    conn = None
    try:
        conn = psycopg2.connect(user = "postgres",
              password = "xxxxxx",
              host = "127.0.0.1",
              port = "5432",
              database = "mydb")
        cur = conn.cursor()
        cur.execute(sql, (select_tables,))
        print(cur.fetchone())
        cur.close()

    """ "myusers" table: id     userid 1      u51884 2      u62194 3      u26922  """
Run Code Online (Sandbox Code Playgroud)

我应该得到:u62194

ajx*_*jxs 7

我认为您错误地使用了查询参数。将列表实例作为参数传递给函数execute以传递查询参数。根据记忆,psycopg2 手册明确不鼓励以您尝试的方式执行此操作。尝试一些更接近这个的东西:

import psycopg2

someuserid = "u62194"

conn = psycopg2.connect(
    user = "postgres",
    password = "xxxxxx",
    host = "127.0.0.1",
    port = "5432",
    database = "mydb"
)

cur = conn.cursor()

# Use a list here to insert query parameters into the query string.
cur.execute(
    """
    SELECT userid 
    FROM myusers u
    WHERE u.userid = %s;
    """,
    [someuserid,]
)

result = cur.fetchone()

print(result)

cur.close()

Run Code Online (Sandbox Code Playgroud)