[英]Python MySQL: Special escaped character leads to insert error
我正在使用參數綁定通過 python 3.x 插入 MySQL 5.7.29。 不知何故,我在插入時仍然遇到插入錯誤'
Failed to save datasets. INSERT IGNORE INTO table (
`name`
)
VALUES ('L\'Test') Error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Test'' at line 1
詢問:
self.curr.execute("""
INSERT IGNORE INTO table (
`name`
)
VALUES (%s)
""", (
item['test'],
)
)
我認為在這種情況下不需要 escaping 嗎?
完整查詢錯誤信息:
Failed to save datasets. INSERT IGNORE INTO manufacturers (name) VALUES ('L\'Oreal Deutschland GmbH Geschäftsbereich La Roche-Posay') Error 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Oreal Deutschland GmbH Geschäftsbereich La Roche-Posay'' at line 1
SQL模式:
SELECT @@sql_mode;
`IGNORE_SPACE,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
MySQL 管道:
class mysql_pipeline(object):
def __init__(self):
self.create_connection()
def create_connection(self):
self.conn = mysql.connector.connect(
host = 'rex',
user = 'crawler',
passwd = 'asdsadf3',
database = 'test',
charset = 'utf8'
)
self.curr = self.conn.cursor()
self.curb = self.conn.cursor(buffered=True)
def process_item(self, item, spider):
self.store_db(item, spider)
return item
def store_db(self, item, spider):
根據您的代碼語法,我假設您使用的是 MySQL 連接器。 你可以這樣寫查詢。
insert_statement = (
"INSERT IGNORE INTO tablename (columnname) " # mind the space after (columnname)
"VALUES (%s)"
)
actual_data = (item['test'],)
cursor.execute(insert_statement, actual_data)
它更易於閱讀,並且完全符合您的要求。
參考: https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
根據錯誤中顯示的語句和錯誤代碼,您的 sql_mode 必須包含 NO_BACKSLASH_ESCAPES。 創建連接后,您可以運行:
self.curr.execute("set @@local.sql_mode=''")
這應該會更改您的連接的 sql_mode。 您可以選擇是否包含其他設置,例如 STRICT_ALL_TABLES
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.