I’m trying to use a variable in a SQL statement however it comes up with the error:
TypeError: function takes at most 2 arguments (3 given)
To be honest, I’m no master programmer and have little experience with postgres so it’s probably quite an easy solution.
Also, if there is another way of doing this that would be very helpful.
Thanks for any help
conn = psycopg2.connect("dbname=postgres user=postgres password=postgres")
cur = conn.cursor()
cur.execute("SELECT password FROM user WHERE email = ",inputed_email,";")
print(cur.fetchone())
cur.close()
conn.close()
2
Answers
This line of code is wrong for two reasons.
First, as the error says, the
execute()
function takes at most two arguments, but you passed three. You can’t just add extra stuff at the end, like you would when you useprint()
.Second, if you want to execute an SQL statement that contains a variable, there is a different way to do that, using placeholders.
Anywhere you want to use a variable in the statement, use
%s
as a placeholder instead:(I don’t know if the
;
at the end is needed. If it is, just add it.)And then the second argument to
execute()
is a list (or a tuple) of all the values that you want to substitute into the query:In this case there is only one value you want to substitute, but the second argument still must be a list, so it’s a list of one item.
If you wanted to execute a query that uses more than one placeholder, it might look like this:
Another option is to use Python F-strings to format the
query
https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals