[Tutor] Didn't take long to hit my next wall!
Brian Gustin
brian at daviesinc.com
Sun Apr 16 19:12:05 CEST 2006
Interesting.. I'll have to dig out my unit test scripts that I wrote to
test the situation to my satisfaction...
The way I had it , I wrote the query exactly as was done in this case,
but I wrote it directly in the cursor.execute() function as in:
cursor.execute('''insert into tablea (id,name,number) values
(%s,%s,%s)'''%(clean_number,injected_text,injected_number))
and the sql injection attacks I had set as testing, were inserted to the
database properly escaped, and never broke.
However, I did not test it as a separate string to be inserted as
cursor.execute(sql_string,%(tuplea,tupleb)), etc.
thanks for the heads up.
Bri!
Kent Johnson wrote:
> Brian Gustin wrote:
>
>>python in this form uses BIND variables..
>> >>query = '''UPDATE cost_grid
>> >> SET cost_1 = %s <--- %s = the bind variable
>>placeholder/formatter
>> >> WHERE cost_grid_id = %s
>> >> AND finish_dro = %s'''' % ( a,c,b) <--- the raw tuple
>>
>>
>> That is, what is provided to python in the tuple following , is
>>formatted as specified by the %s , and as such, is a formatted string
>>(special characters are properly esscaped), and as far as sql query is
>>concerned, it is escaped safely..
>
>
> No. There are two ways to write this that look very similar but act very
> differently. To simplify the example a bit, suppose the query is
> query = '''update cost_grid set cost_1 = %s where cost_grid_id = %s'''
> and the values for cost_1 and cost_grid_id are in variables a and b.
>
> If you write
> cursor.execute(query % (a, b))
>
> then you are using string formatting to put the values into the query.
> This is problematic when a or b needs to be escaped in any way, and is
> open to SQL injection attacks.
>
> On the other hand, if you write
> cursor.execute(query, (a, b))
>
> then the values are passed as a separate parameter to execute(). In this
> case the DB wrapper will properly escape the values.
>
> Kent
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
> !DSPAM:44426e80136686683119212!
>
>
More information about the Tutor
mailing list