Python mysql - sufficiently prepared statements or do i need escape_string ()?

Like this:

cursor.execute("Insert INTO visit (pid, date, diagnosisid) VALUES (%s,%s,%s)", (pid, date, diagnosisid)) 

enough or i need:

 cursor.execute("Insert INTO visit (pid, date, diagnosisid) VALUES (%s,%s,%s)", (escape_string(pid), escape_string(date), escape_string(diagnosisid))) 

?

+4
source share
3 answers

The first is enough; the second is to redouble your efforts, replacing, for example, " c \" . You can check it yourself using

 >>> c.execute("SELECT %s, %s", ('"', MySQLdb.escape_string('"'))) 1L >>> c.fetchall() ((u'"', u'\\"'),) 

So you see that the second version will create an unnecessary \ before. " So, the first one is fine.

+3
source

The first code sample is already safe for SQL injection. The second example will cause extra quotes in your database, which is most likely not what you want.

+3
source

As long as this is not a formatted string, and they are really ready-made statements, you do not have to worry.

This can cause more problems than it should be avoided twice.

0
source

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


All Articles