MySQL-automatic escape of parameters in python

Summary

Use the placeholder described in Cursor.execute (self, query, args = None) when building queries using Python's MySQL-python (MySQLdb) module.

query -- string, query to execute on server
args -- optional sequence or mapping, parameters to use with query.

Note: If args is a sequence, then %s must be used as the
parameter placeholder in the query. If a mapping is used,
%(key)s must be used as the placeholder.

Test table

Create the following table for testing.

mysql> select * from testdb.person;
+------+--------+
| id   | name   |
+------+--------+
|    1 | foo    |
|    2 | bar    |
+------+--------+

bad example

bad.py


import MySQLdb


def select(name):
    connection = MySQLdb.connect(db='testdb', user='testuser')
    cursor = connection.cursor()
    cursor.execute("select * from person where name='%s'" % name)
    print("[query]")
    print(cursor._last_executed)
    print("[result]")
    result = cursor.fetchall()
    for rec in result:
        print(rec)

If you do select ("foo "), it looks like it's working nicely.

[query]
select * from person where name='foo'
[result]
(1L, 'foo')

But if you do something like select ("foo' or name = name--")

[query]
select * from person where name='foo' or name=name-- '
[result]
(1L, 'foo')
(2L, 'bar')

And SQL injection is done.

Good example

good.py


import MySQLdb


def select(name):
    connection = MySQLdb.connect(db='testdb', user='testuser')
    cursor = connection.cursor()
    cursor.execute("select * from person where name=%s", name)
    print("[query]")
    print(cursor._last_executed)
    print("[result]")
    result = cursor.fetchall()
    for rec in result:
        print(rec)

I changed only the argument part of cursor.execute ().

With select ("foo "), it works the same as in the previous example.

[query]
select * from person where name='foo'
[result]
(1L, 'foo')

Even if you do select ("foo' or name = name-- "), it will escape properly.

[query]
select * from person where name='foo\' or name=name-- '
[result]

References

http://stackoverflow.com/questions/1947750/does-python-support-mysql-prepared-statements

Recommended Posts

MySQL-automatic escape of parameters in python
Equivalence of objects in Python
Implementation of quicksort in Python
Pixel manipulation of images in Python
Division of timedelta in Python 2.7 series
Handling of JSON files in Python
Implementation of life game in Python
Waveform display of audio in Python
Law of large numbers in python
Implementation of original sorting in Python
Reversible scrambling of integers in Python
Coursera Machine Learning Challenges in Python: ex5 (Adjustment of Regularization Parameters)
Conversion of string <-> date (date, datetime) in Python
Check the behavior of destructor in Python
(Bad) practice of using this in Python
General Theory of Relativity in Python: Introduction
Output tree structure of files in Python
Display a list of alphabets in Python 3
Comparison of Japanese conversion module in Python3
Summary of various for statements in Python
The result of installing python in Anaconda
Gang of Four (GoF) Patterns in Python
The basics of running NoxPlayer in Python
Bulk replacement of strings in Python arrays
Project Euler # 16 "Sum of Powers" in Python
Traffic Safety-kun: Recognition of traffic signs in Python
Summary of built-in methods in Python list
Non-logical operator usage of or in python
In search of the fastest FizzBuzz in Python
Practical example of Hexagonal Architecture in Python
Project Euler # 17 "Number of Characters" in Python
Double pendulum equation of motion in python
Get rid of DICOM images in Python
Status of each Python processing system in 2020
Project Euler # 1 "Multiples of 3 and 5" in Python
[Python] Expand escape sequences in here documents
Meaning of using DI framework in Python
Quadtree in Python --2
Python in optimization
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
Introduction of Python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
Basics of Python ①
Basics of python ①
Programming in python
Plink in Python
Constant in python
Copy of python
Lifegame in Python.
FizzBuzz in Python