0

I'm using mysqlclient (fork of MySQLdb1 for python3) in Python 3.4.3, and according to what I've read online (Escape string Python for MySQL), MySQLdb Python queries should be written like this for proper escaping:

query = self.conn.cursor()
query.execute('SELECT 1 FROM servers WHERE ip=%s AND port=%s AND game_id=%s' ,(ip,port,gameid))

Unfortunately, when I do that, I get the following error:

unsupported operand type(s) for %: 'bytes' and 'tuple' mysqldb

This appears to work, but this could lead to SQL injection?

query = self.conn.cursor()
query.execute("SELECT 1 FROM servers WHERE ip='%s' AND port=%s AND game_id='%s'" % (ip,port,gameid))

So, how do I safely get the query above to work using the preferred syntax method that will escape it all for me in Python 3.4.3?

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
OwN
  • 1,248
  • 12
  • 17
  • So far I know "Parameterized query and Prepared Statement" are the best way to prevent sql injection with python. You are in the right direction in my opinion. See [this](https://pynative.com/python-mysql-execute-parameterized-query-using-prepared-statement/) for more. – Novy Mar 22 '19 at 18:03
  • Please show the full traceback, and the values of `ip`, `port` and` gameid`. Note that as you suspect, you must never ever use your second code. – Daniel Roseman Mar 22 '19 at 18:17
  • ip `68.232.163.47` port `12203` gameid `mohaa` - couldn't get it to work unless I used the bad way... it would always give me that `unsupported operand types` error. – OwN Mar 22 '19 at 18:34
  • Maybe I just need to convert those params to strs? `str(ip), str(port), str(gameid)`? – OwN Mar 22 '19 at 18:36
  • Nope. that didn't work. I have no idea why this is happening. – OwN Mar 23 '19 at 04:03

2 Answers2

0

I couldn't get mysqlclient (a fork of MySQLdb) https://pypi.org/project/mysqlclient/ to work with Python 3.4 with the proper SQL syntax (the syntax that escapes everything for you). I switched to mysql-connector, and the same query code now works fine. It looks like a bug in mysqlclient.

pip3 install mysql-connector-python

https://pypi.org/project/mysql-connector-python/

OwN
  • 1,248
  • 12
  • 17
0

mysqlclient-python doesn't support Python 3.4 anymore. Use newer Python.

methane
  • 469
  • 3
  • 5
  • 11