I am trying to get more familiar with placeholders to to run SQL commands from python, but cannot successfully pass character commands. Here I describe a simplified solution that will be scaled up. In python I can create a basic SQL query using a placeholder
sql = 'SELECT * FROM schema.my_table\nLIMIT %s'
And set up to run the command wrapped in a function which takes the sql command plus a value (a limit to the number of rows).
def my_function(query, value):
conn=pg_engine().raw_connection()
with conn.cursor() as conn:
cursor.execute(query, value)
conn.commit()
return rowcount
This can successfully run if I, for example, do my_function(sql, [10])
, but if I try to run my_function(sql, ['ALL'])
then I receive an error
invalid input syntax for type bigint
So it is clearly expecting a numeric value; is there a different way of passing a character string in this instance, or another way of addressing this problem?
Thanks
CodePudding user response:
A quick example
import psycopg2
from psycopg2 import sql
sql_str = sql.SQL('SELECT * FROM schema.my_table LIMIT {}').format(sql.SQL('ALL'))
print(sql_str.as_string(con))
SELECT * FROM schema.my_table LIMIT ALL
Though to be honest sql.SQL
is not escaped.
You can get the same effect doing:
sql_str = sql.SQL('SELECT * FROM schema.my_table LIMIT {}').format(sql.Literal(None))
print(sql_str.as_string(con))
SELECT * FROM schema.my_table LIMIT NULL
This uses sql.Literal
which is safer.