代码如下(我是Python / Mysql的新手):
import mysql.connector
conn = mysql.connector.connect(host='localhost',user='user1',password='puser1',db='mm')
cursor = conn.cursor()
string1 = 'test1'
insert_query = """INSERT INTO items_basic_info (item_name) VALUES (%s)""", (string1)
cursor.execute(insert_query)
conn.commit()
当我运行此代码时,我收到此错误:
Traceback (most recent call last)
File "test3.py", line 9, in <module>
cursor.execute(insert_query)
File "C:\Users\Emanuele-PC\AppData\Local\Programs\Python\Python36\lib\site-packages\mysql\connector\cursor.py", line 492, in execute
stmt = operation.encode(self._connection.python_charset)
AttributeError: 'tuple' object has no attribute 'encode'
我已经看到了这个问题的不同答案,但案例与我的情况完全不同,我无法真正理解我在哪里犯错误。任何人都可以帮助我吗?
答案 0 :(得分:3)
对于avoid SQL-injections Django documentation完全建议使用这样的占位符:
import mysql.connector
conn = mysql.connector.connect(host='localhost',user='user1',password='puser1',db='mm')
cursor = conn.cursor()
string1 = 'test1'
insert_query = """INSERT INTO items_basic_info (item_name) VALUES (%s)"""
cursor.execute(insert_query, (string1,))
conn.commit()
你必须在execute方法中传递tuple / list params作为第二个参数。一切都应该没问题。
答案 1 :(得分:0)
不完全是OP的问题,但我在将多个变量写入MySQL时卡了一段时间。
根据Jefferson Houp的答案,如果添加多个字符串,则必须在“ cursor.execute”函数中指定参数“ multi = True”。
import mysql.connector
conn = mysql.connector.connect(host='localhost',user='user1',password='puser1',db='mm')
cursor = conn.cursor()
string1 = 'test1'
string2 = 'test2'
insert_query = """INSERT INTO items_basic_info (item_name) VALUES (%s, %s)"""
cursor.execute(insert_query, (string1, string2), multi=True)
conn.commit()