Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python mysql.connector转义字符串_Python_Mysql - Fatal编程技术网

使用python mysql.connector转义字符串

使用python mysql.connector转义字符串,python,mysql,Python,Mysql,我正在尝试使用python和SQL将一组字符串插入mysql。我当前的代码如下所示: db = mysql.connector.Connect('config blah blah') cursor = db.cursor() data = (somestring1, somestring2) sql = "INSERT INTO mytable (col1, col2) VALUES ('%s', '%s')" cursor.execute(sql, data) 我该如何摆脱束缚呢?我可以尝试

我正在尝试使用python和SQL将一组字符串插入mysql。我当前的代码如下所示:

db = mysql.connector.Connect('config blah blah')
cursor = db.cursor()
data = (somestring1, somestring2)
sql = "INSERT INTO mytable (col1, col2) VALUES ('%s', '%s')"
cursor.execute(sql, data)
我该如何摆脱束缚呢?我可以尝试用python来做,但我知道这不是正确的方法

注意:我意识到mysql.connector仍在开发中

更新:

第4行应改为:

sql = "INSERT INTO mytable (col1, col2) VALUES (%s, %s)"
由于mysql.connector是兼容的,您不需要自己转义数据,它会自动为您转义数据。

答案是最好的方法

但是,如果确实需要转义一些任意字符串,可以这样做(在2.1.6之前):

较新版本(使用低级C-API):


实际上,最好的方法是让模块本身转义值。如果您确实需要手动执行(例如,我只想在脚本的调试模式下打印SQL,并且
mysql.connector
似乎没有实现
mogrify()
),还有另一个选项:

>>>> import mysql.connector
>>>> cnx = mysql.connector.connect()
>>>> cur = cnx.cursor()
>>>> cur._connection.converter.escape("tic ' toc")
"tic \\' toc"

诚然,它仍然使用“非公共API”,但至少在最新版本之间是一致的(到目前为止,在2.0.4、2.1.3、2.2.9、8.0.16上进行了测试)。

谢谢。我实际上正确地输入了示例代码。我对它进行了编辑以显示我的问题。如果必须生成包含1000(10000,1000000)个值的insert语句,则必须使用
%s
对其进行硬编码?如果您不知道必须插入多少值,例如,如果您从外部源(文件、HTTP请求)读取,该怎么办?如何使用“自动转义”?还有一个例外:mysql connector python目前不支持列表或元组参数。例如,您不能在提供的字符串列表中形成子句。因此,库调用者负责转义列表。如果表名包含连字符,则必须使用反勾号转义,否则将得到
mysql.connector.errors.ProgrammingError
这对我不起作用,我得到AttributeError:'NoneType'对象没有属性“escape”Hi@IvanIvković,您使用的是哪个版本?刚刚又测试了一次,效果很好:)我使用的是2.1.4,你使用的是mysql网站上的mysql.connector吗?嗨@Luciano Barcaro,我会尝试回滚到2.1.4,因为我现在使用的是2.1.6。谢谢你的帮助,尤其是在我生日那天!新版本不起作用:(但是,我找到了另一种方法:import _mysql_connector db=_mysql_connector.mysql()db.connect(主机…,用户…)转义_string=db.escape_string('teststring'))它来自低级C-API。编辑主要答案。一个前导下划线表示不应在库本身之外使用的实现细节。它可以在任何新版本中更改名称或语义,而无需通知。
db = mysql.connector.connect(......)

new_str = db._cmysql.escape_string('string to be escaped')
>>>> import mysql.connector
>>>> cnx = mysql.connector.connect()
>>>> cur = cnx.cursor()
>>>> cur._connection.converter.escape("tic ' toc")
"tic \\' toc"