B
B
butroskali2020-11-24 21:17:48
Python
butroskali, 2020-11-24 21:17:48

Parameterization of sql query psycopg2, how to pass the content of two variables to the query body?

It is necessary to pass 2 variables to the body of the sql request.
The official documentation says that parameters are passed through a variable as follows, but this only works with one parameter:

SQL = "INSERT INTO authors (name) VALUES (%s);" # Note: no quotes
data = ("O'Reilly", )
cur.execute(SQL, data)

how would it be possible to pass two variables, that is, something like this:
SQL = "INSERT INTO authors (%s) VALUES (%s);" 
data_1 = ("name",)
data_2 = ("O'Reilly", )
cur.execute(SQL, data_1,data_2)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2020-11-24
@galaxy

Exactly as you wrote it is not possible. It is possible like this :


Only query values ​​should be bound via this method: it shouldn't be used to merge table or field names to the query (Psycopg will try quoting the table name as a string value, generating invalid SQL). If you need to generate dynamically SQL queries (for instance choosing dynamically a table name) you can use the facilities provided by the psycopg2.sql module:
>>> cur.execute("INSERT INTO %s VALUES (%s)", ('numbers', 10))  # WRONG
>>> cur.execute(                                                # correct
...     SQL("INSERT INTO {} VALUES (%s)").format(Identifier('numbers')),
...     (10,))


however, this is not fundamentally different from str.format().

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question