skip to Main Content

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

inputed_email is a variable that matches one of the records in the user table

2

Answers


  1. cur.execute("SELECT password FROM user WHERE email = ",inputed_email,";")
    

    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 use print().

    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:

    SELECT password FROM user WHERE email = %s
    

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

    cur.execute("SELECT password FROM user WHERE email = %s", [inputed_email])
    

    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:

    cur.execute("SELECT password FROM user WHERE email = %s and lastname = %s", [email, lastname])
    
    Login or Signup to reply.
  2. Another option is to use Python F-strings to format the
    query

    cur.execute(f"SELECT password FROM user WHERE email = {inputed_email};")
    

    https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search