'tuple' object has no attribute 'encode'
Asked Answered
S

2

5

The code is the following (I am new to 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()

When I run this code I get this error:

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'

I have seen different answers to this problem but the cases were quite different from mine and I couldn't really understand where I am making mistakes. Can anyone help me?

Subarid answered 3/9, 2017 at 1:52 Comment(0)
H
6

For avoid SQL-injections Django documentation fully recommend use placeholders like that:

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()

You have to pass tuple/list params in execute method as second argument. And all should be fine.

Highstepper answered 3/9, 2017 at 5:10 Comment(0)
T
0

Not exactly OP's problem but i got stuck for a while writing multiple variables to MySQL.

Following on from Jefferson Houp's answer, if adding in multiple strings, you must specify the argument 'multi=True' in the 'cursor.execute' function.

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()
Taffrail answered 4/3, 2020 at 15:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.