-1

I have the following function which executes a query on a PostgreSQL db:

def execute_query(query):
    con, cur = connect_to_db()
    cur.execute(query)
    con.commit()
    con.close()

When I try to submit a query which includes %s, the %s is considered as an additional argument, which produces the following error:

TypeError: execute_query() takes 1 positional argument but 2 were given

How can I include %s without producing this error? Sample:

execute_query( """ DELETE FROM table WHERE column = %s """, [x[0]])
Laurie
  • 1,189
  • 1
  • 12
  • 28
  • https://xkcd.com/327/ - dont use strings to create query strings - use parameters – Patrick Artner Oct 21 '18 at 18:56
  • see [parameterized-queries-with-psycopg2-python-db-api-and-postgresql](https://stackoverflow.com/questions/1466741/parameterized-queries-with-psycopg2-python-db-api-and-postgresql) - you can provide both to your functions: `def execute_query(query, *args): ...` – Patrick Artner Oct 21 '18 at 18:57
  • 1
    You should learn about args and kwargs. – Mike Scotty Oct 21 '18 at 18:59

1 Answers1

1

you just need to accept an extra param...

def execute_query(query, args):
    con, cur = connect_to_db()
    cur.execute(query,args)
    con.commit()
    con.close()

although you should also look into args and kwargs and unpacking

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
  • Thanks, I'm I tried this and it didn't work but it seems to be working now for some reason.. – Laurie Oct 21 '18 at 19:04