I am trying to insert a bunch of strings into mysql using python and mysql.connector. My current code looks something like this:
我试图使用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)
How should I go about escaping my strings? I could try doing it in python but I know this isn't the right way.
我应该怎么逃避我的弦?我可以尝试在python中进行,但我知道这不是正确的方法。
Note: I realise mysql.connector is still in development.
注意:我意识到mysql.connector仍处于开发阶段。
update:
更新:
Line 4 should read:
第4行应为:
sql = "INSERT INTO mytable (col1, col2) VALUES (%s, %s)"
2 个解决方案
#1
8
Since mysql.connector is DB API v2.0 compliant, you do not need to escape the data yourself, it does it automatically for you.
由于mysql.connector符合DB API v2.0,因此您无需自行转义数据,它会自动为您执行。
#2
9
The answer from infrared is the best approach.
红外线的答案是最好的方法。
But, if you really need to escape some arbitrary string, you can do this:
但是,如果你真的需要逃避一些任意的字符串,你可以这样做:
db = mysql.connector.connect(......)
new_str = db.converter.escape('string to be escaped')
#1
8
Since mysql.connector is DB API v2.0 compliant, you do not need to escape the data yourself, it does it automatically for you.
由于mysql.connector符合DB API v2.0,因此您无需自行转义数据,它会自动为您执行。
#2
9
The answer from infrared is the best approach.
红外线的答案是最好的方法。
But, if you really need to escape some arbitrary string, you can do this:
但是,如果你真的需要逃避一些任意的字符串,你可以这样做:
db = mysql.connector.connect(......)
new_str = db.converter.escape('string to be escaped')