<br><br><div class="gmail_quote">On Tue, Mar 3, 2009 at 2:04 PM, Tim Allen <span dir="ltr">&lt;<a href="mailto:screwtape@froup.com">screwtape@froup.com</a>&gt;</span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
<div><div></div><div class="h5">On Tue, Mar 03, 2009 at 01:17:48PM +0100, Pet wrote:<br>
&gt; what is a proper way to escape user input in database query strings?<br>
&gt; I&#39;ve used quote from twisted.enterprise.util, but it is deprecated now.<br>
&gt; Is there any other module for this purpose?<br>
<br>
</div></div>The correct way to escape user input is not to do it at all, but rather<br>
to leave it up to the DB-API module you&#39;re using:<br>
<br>
    from twisted.enterprise.adbapi import ConnectionPool<br>
<br>
    pool = ConnectionPool(&quot;psycopg2&quot;)<br>
    d = pool.runQuery(&quot;&quot;&quot;<br>
        SELECT *<br>
        FROM students<br>
        WHERE name = %s<br>
        &quot;&quot;&quot;, &quot;Robert &#39;); DROP TABLE students;--&quot;)<br>
<br>
Note that although I&#39;ve used &quot;%s&quot; in the query, this is not normal<br>
Python string-formatting, the &quot;%s&quot; is just tells the DB-API module I&#39;m<br>
using (in this case, psycopg2 for PostgreSQL) to quote one of the extra<br>
parameters and insert in that spot. Look up &quot;paramstyle&quot; in the DB-API<br>
spec[1] and the documentation for the DB-API module you&#39;re using for<br>
more details.<br>
<br>
[1] <a href="http://www.python.org/dev/peps/pep-0249/" target="_blank">http://www.python.org/dev/peps/pep-0249/</a><br>
<div><div></div><div class="h5"><br>
_______________________________________________<br>
Twisted-Python mailing list<br>
<a href="mailto:Twisted-Python@twistedmatrix.com">Twisted-Python@twistedmatrix.com</a><br>
<a href="http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python" target="_blank">http://twistedmatrix.com/cgi-bin/mailman/listinfo/twisted-python</a><br>
</div></div></blockquote></div><br><br>Thanks for all your answers! It works fine in that way. But what, if I compose my query? For example:<br><br>def getData(self, type=&#39;&#39;):<br>    id = 1<br>    if type:<br>        str = &quot; AND mytype = %s &quot; % type<br>
    str = &#39;&#39;<br>    query = &quot;SELECT * FROM table WHERE id = %s %s &quot; % (id,str)<br>    cur.execute(query)<br><br>I mean, str part is not always there and I need escape it only if type is passed to function<br>
<br>Thanks, Pet<br><br><br>