使用python mysql.connector转义字符串

Mr_*_*imp 11 python mysql

我试图使用python和mysql.connector将一堆字符串插入到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)
Run Code Online (Sandbox Code Playgroud)

我应该怎样逃避我的弦?我可以尝试在python中进行,但我知道这不是正确的方法.

注意:我意识到mysql.connector仍处于开发阶段.

更新:

第4行应为:

sql = "INSERT INTO mytable (col1, col2) VALUES (%s, %s)"
Run Code Online (Sandbox Code Playgroud)

Luc*_*aro 15

红外线的答案是最好的方法.

但是,如果你真的需要逃避一些任意的字符串,你可以这样做(在2.1.6之前):

db = mysql.connector.connect(......)

new_str = db.converter.escape('string to be escaped')
Run Code Online (Sandbox Code Playgroud)

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

db = mysql.connector.connect(......)

new_str = db._cmysql.escape_string('string to be escaped')
Run Code Online (Sandbox Code Playgroud)

  • 这对我不起作用,我得到 AttributeError: 'NoneType' object has no attribute 'escape' (3认同)

inf*_*red 10

由于mysql.connector 符合DB API v2.0,因此您无需自行转义数据,它会自动为您执行.

  • 如果您必须生成包含 1000 (10,000, 1,000,000) 个值的插入语句,您必须使用 `%s` 对其进行硬编码怎么办?如果不知道要插入多少值怎么办,比如从外部源(文件、HTTP请求)读取怎么办,如何使用“自动转义”? (2认同)
  • 还有另一个例外:mysql-connector-python 目前不支持列表或元组参数。比如说,您无法形成提供字符串列表的 IN 子句。因此,库调用者负责转义列表。 (2认同)