I’ve notice most sources say to best practice to execute SQL statements in Python is something like this:
cursor.execute( 'select * from coworkers where name = :1 and clue > :2', [ name, clue_threshold ] )
Other sources say
cursor.execute( "select * from coworkers where name = %s and clue > %s", ( name, clue_threshold ) )
which I think is pretty similar.
Anyway the way I have been doing is creating a dictionary and storing values. For example, the initial dictionary biz_info looks like this:
biz_info = {
'business' : None,
'name' : None,
'neighborhood' : None,
'address' : None,
'city' : None,
'state' : None,
'zip_code' : None,
'latitude' : None,
'longitude' : None,
'phone' : None,
'url' : None,
'yelp_url' : None,
}
then I execute the SQL statement like this
execute_sql( cur, "insert into " + TABLE_BIZ_NAME + """ values (
NULL,
%(name)s,
%(neighborhood)s,
%(address)s,
%(city)s,
%(state)s,
%(zip_code)s,
%(latitude)s,
%(longitude)s,
%(phone)s,
%(url)s,
%(yelp_url)s,
NULL
)"""
, biz_info )
Is this safe against sql injections? I want to use dictionaries to store information because it’s easier to manage.
To be honest, I’m not even entirely sure what the difference between using a %, ,, %s, %d, and %()s means in parameterized queries. Basically all I know is not to use
cursor.execute( "select * from coworkers where name = '%s' and clue > %d" % ( name, clue_threshold ) )
The way used to pass parameters to sql command strings depends on the database (sqlite, for example, uses
?).According to MySQLdb documentation, you can use
paramstyleparameter to set the preferred way to format a string (formatorpyformat).The first example in your question doesn’t seem to be supported. Anyway, I’d say that as long as you don’t format the whole string as in the last example, you’re safe since it can be assumed that the query parameters will be properly escaped.