Psycopg2 variable format for creating queries

It's not that important, so I'm just curious to know the following (Python 2.7):

I just started using psycopg and reading through documents, they always use strings (% s) and tuples to pass values ​​to the request.

Variable placeholder must always be% s

So, consider the following example -

In a table named "test" with the fields value_1 (varchar) and value_2 (int), the query is created as:

value_1 = "test"
value_2 = "100"
cur.execute("INSERT INTO test (value_1,value_2) VALUES (%s,%s)",\
           (value_1,value_2))

My question is, is this a bad practice or is it even problematic to use the 'format' method instead:

cur.execute("INSERT INTO test (value_1,value_2) VALUES ('{value1}',{value2})".\
           format(value1=value_1,value2=value_2))

What do you say, based on your experience, is it really dangerous or problematic?

+4
source share
3 answers

Call

cur.execute("INSERT INTO test (value_1,value_2) VALUES (%s,%s)",\
           (value_1,value_2))

, . psycopg2 , .

docs psycopg2

; , Psycopg

; ( SQL-!)

→ > cur.execute( "INSERT INTO test (num, data) VALUES (% s,% s)",... (100, "abc'def" ))

cur.execute("INSERT INTO test (value_1,value_2) VALUES ('{value1}',{value2})".\
           format(value1=value_1,value2=value_2))

.

SQL-. , .

" " .

+4

, . : . psycopg2, db ( , , ). psycopg2 (% s) () psycopg2 , .

, :

cur.execute("INSERT INTO test (value_1,value_2) VALUES ('{value1}','{value2}')".\
format(value1=value_1,value2='1); drop table test; --killer instinct'))

, adiós:-P

+1

, Psycopg2 % s , psycopg2

INSERT INTO test (value_1,value_2) VALUES('test','100');

.

 cur.execute("""INSERT INTO test (value_1,value_2) 
       VALUES (%s,%s::integer)""",
       (value_1,value_2))

- , sql value_1 value_2. :

 value_1="',0); rollback; drop table test ; --"
+1

All Articles