Python: insert double or single quotes around a string

I use python to access the MySQL database and im getting an unknown column in the field due to the absence of quotes around the variable.

below:

cur = x.cnx.cursor()
cur.execute('insert into tempPDBcode (PDBcode) values (%s);' % (s)) 
rows = cur.fetchall()

How to manually insert double or single quotes around an s value? I am trying to use str()and manually concatenate quotes around s, but it still doesn't work. The sql statement works fine iv double and triple validates my SQL query.

+3
source share
3 answers

You should not use Python string functions to build SQL statements. You risk leaving a SQL injection vulnerability. You should do this instead:

cur.execute('insert into tempPDBcode (PDBcode) values (%s);', s) 

Pay attention to the comma.

+10

Python , API :

cur = x.cnx.cursor()
cur.execute('insert into tempPDBcode (PDBcode) values (%s)',s) 

API , python , , , SQL-, s , ,

value'); drop database; '
+5

If this were a question related to a string, the answer would simply be to put them in a string:

cur.execute('insert into tempPDBcode (PDBcode) values ("%s");' % (s)) 

This is a classic example of using Python to support both kinds of quotes.

However, as other answers and comments pointed out, SQL issues are important in this case.

-4
source

Source: https://habr.com/ru/post/1736801/


All Articles