0

I'm new to python. Previously I used PHP with MySQL; now learning python. At this point, I'm learning to work with MySQL.

I have connected to the database using the code bellow:

import mysql.connector

cnx = mysql.connector.connect(user="myUser", password="myPass", host="localhost", database="myDb")

The connection seems to work properly and I can query items from the database using the "cursor":

sql = "SELECT * FROM..."

cnx.cursor.execute(sql)

The problem is, when I use the "escape_string" method of the connection like bellow:

escaped_string = cnx.escape_string("some SQL invalid 'terms'")

I get :

AttributeError: 'MySQLConnection' object has no attribute 'escape_string'.

I thought it's a bug related to the mysql_connector, so I thought updating may help.

pip install --upgrade mysql_connector

This updated mysql_connector but didn't solve the problem.

I'm using python 3.7.1 and mysql_connector 2.1.6

Mark Amery
  • 143,130
  • 81
  • 406
  • 459
Hosnee Zaman
  • 11
  • 1
  • 4
  • I know nothing about Python but, in general, string escaping is an obsolete technique that's very popular in programming tutorials. The proper way to inject external input is to use prepared statements (and it's also easier and more concise). – Álvaro González Dec 25 '18 at 10:10
  • A pointer: per the docs, `escape_string` is a method of the `MySQL` class (see https://dev.mysql.com/doc/connector-python/en/connector-python-api-cext-escape-string.html), not of the `MySQLConnection` class (whose methods are listed at https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlconnection.html). I don't know the library well enough to advise any further than that. – Mark Amery Dec 25 '18 at 12:54
  • @ÁlvaroGonzález You're right. It's the better approach.However, I saw few examples using escape_string on connection and wanted to try myself and got confused when found it not working in my code. So, raised the question. – Hosnee Zaman Dec 25 '18 at 16:58
  • @MarkAmery You found i! This is the right reason. I might have messed up myself between the mysql.connector and MySQLdb api. – Hosnee Zaman Dec 25 '18 at 17:02

1 Answers1

1

I can't find out why this is happening to you, but you can create your own escape_string using python. Don't do:

sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)" % (val1, val2)
cursor.execute(sql)

Do:

sql = "INSERT INTO TABLE_A (COL_A,COL_B) VALUES (%s, %s)"
cursor.execute(sql, (val1, val2))

You can follow these links to find out more solutions: Escape string Python for MySQL and Escape string Python for MySQL _ Stack overflow

Ali Akhtari
  • 1,211
  • 2
  • 21
  • 42
  • 1
    I have reviewed them already. The reason has been pointed out by MarkAmery. I've found your guideline to be great and will be following for sure. Thanks. – Hosnee Zaman Dec 25 '18 at 17:07