I think you're using the query parameters incorrectly. Pass a list instance as a parameter to the execute function to pass your query parameters. From memory the psycopg2 manual explicitly discourages doing this in the manner you were trying.
Try something closer to this:
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()
Answer from ajxs on Stack OverflowHelp with properly executing SELECT * query with psycopg2
Parameterized queries with psycopg2: SELECT from a Python list - Stack Overflow
(Python psycopg) How do I add additional WHERE … AND … conditions to a SQL statement?
Fetching by batch (1M+ records)
Hi All,
So I've got a simple postgres database setup that I populated using the Python psycopg2 library.
I want to run a SELECT * query using psycopg2's cursor object, however None is returned when I run the query. This is odd because running the same query from psql command line returns my database.
Basically, here's my code that only produces None
conn = psycopg2.connect(dbname='cooking', user='me', host='localhost')
cur = conn.cursor()
print(cur.execute("SELECT * FROM dishes;"))
cur.close()
conn.close()And here is a work around I produced using Pandas.
conn = psycopg2.connect(dbname='cooking', user='sean', host='localhost') sql_query = "SELECT * FROM dishes" print(pd.read_sql(sql_query, con=conn)) conn.close()
This gives me the desired output. Can someone aid me so that I only need psycopg2, and can avoid the overhead associated with Pandas?
Using psycopg, I’d like to build a SQL statement according to certain conditions. There would be a base SELECT query, and then append WHERE. And then append AND. And then append another AND, etc.
I appreciate help on this!