@yukharpaev

Как сравнить с подстрокой без sql-инъекций?

Запрос формируется в python-модуле.
База данных - PostgreSQL.

В sql-запросе есть сравнение с подстрокой:
'''
SELECT *
FROM TableTemp
WHERE "SomeColumn" LIKE '%{0}%'
'''.format(<some_string>)

Если строкой будет:
%' --
то проверка всегда будет возвращать "True".
Дополнительно, можно сделать sql-инъекцию

Подскажите, как правильно обработать строку, чтобы она учитывалась при поиске, но не портила запрос и не было sql-инъекций?
  • Вопрос задан
  • 371 просмотр
Пригласить эксперта
Ответы на вопрос 1
sim3x
@sim3x
initd.org/psycopg/docs/usage.html#query-parameters

Psycopg casts Python variables to SQL literals by type. Many standard Python types are already adapted to the correct SQL representation.

Example: the Python function call:

>>> cur.execute(
...     """INSERT INTO some_table (an_int, a_date, a_string)
...         VALUES (%s, %s, %s);""",
...     (10, datetime.date(2005, 11, 18), "O'Reilly"))
is converted into the SQL command:


INSERT INTO some_table (an_int, a_date, a_string)
 VALUES (10, '2005-11-18', 'O''Reilly');

Named arguments are supported too using %(name)s placeholders. Using named arguments the values can be passed to the query in any order and many placeholders can use the same values:

>>> cur.execute(
...     """INSERT INTO some_table (an_int, a_date, another_date, a_string)
...         VALUES (%(int)s, %(date)s, %(date)s, %(str)s);""",
...     {'int': 10, 'str': "O'Reilly", 'date': datetime.date(2005, 11, 18)})
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы