简体   繁体   中英

How to quote string in python using “mysql.connector”

I'm newbie to python and writing a script that reads json file, do some processing, and generate SQL statements that finally is written to a sql file. I'm using mysql.connector on python 3.6 to create connection.

From that connection object, I need to quote the parameters that are binded to the SQL. I'm not executing SQL from python, otherwise python itself would have handled it.

Also, I'm not directly using single/double quotes as my value may contain these quotes and sql will break. Moreover, there are many characters that needs to be quoted, so can't be sure after replacing just one character (say single quote).

Sample Code:

import mysql.connector
con = mysql.connector.connect(user=user, password=pwd, database=database, host=host)
sql = "INSERT INTO customer_data VALUES "

values = "(default, %s, %s, %s);" % (
            cust_record["name"],
            cust_record["address"],
            comment["date"]
            )

fh.write("%s %s\n" % (sql, values))

It writes string as it is while creating insert statement, I avoided putting hardcoded single quotes.

I also tried this on console for testing:

name = 'kam\al'
str = ("my name is %s" % name)
con.converter.escape(str)

It gives: 'my name is kam\\x07l' , without quoting the name string. Same in perl can be achieved via perl DBI's quote method.

Updated

You can use convert_to_mysql() if you want both, and construct the connection in a different way. Here's an example (Python 3.6):

import _mysql_connector
ccnx.connect(user='abc', database='xyz', password='def')
params = ('sdgs\adsgsdg', 'sdgs^&%"', "sdgsdg'") 
print(ccnx.convert_to_mysql(*params)) 

Will output:

(b"'sdgs\x07dsgsdg'", b'\'sdgs^&%\\"\'', b"'sdgsdg\\''")

They are already quoted and escaped. Note that they are bytes (python 3) so you might need to convert them to str (depndeing on your python version.

See: _mysql_connector.MySQL.convert_to_mysql() Method

Old answer

Don't construct queries that way, you may open yourself to SQL injection and other issues.

Use prepared statements, let the driver do the quoting for you, eg:

stmt = "INSERT INTO names (name) VALUES (%s)"
name = "Some name' who cares"

cursor.execute(stmt, (name,))

For more info see: Inserting Data Using Connector/Python

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM