I am trying to read JSON from a file and insert it into a MySQL database. But I am getting the following error:
Traceback (most recent call last):
File "loopedadd.py", line 44, in <module>
cursor.execute(add_record, data_record)
File "/Library/Python/2.7/site-packages/mysql/connector/cursor.py", line 536, in execute
stmt = operation.encode(self._connection.python_charset)
AttributeError: 'function' object has no attribute 'encode'
I have tried connecting with use_unicode=True, charset='utf8'
to no avail.
Any help on how to fix this error would be greatly appreciated.
My code is as follows:
import mysql.connector
import Queue, json
cnx = mysql.connector.connect(user="root",
host="192.168.1.64",
password="....",
database="records",
port=3306)
print("connected")
cursor = cnx.cursor()
queue = Queue.Queue()
content = json.load(open("data.txt","r"))
for jsonobj in content:
queue.put(jsonobj)
add_record = (
"INSERT INTO records "
"(id, timestamp, location, value, unit) "
"VALUES (%s, %s, %s, %s, %s)")
while not queue.empty():
values = queue.get()
data_record = (values['id'], values['timestamp'],
values['location'], values['reading'], values['unit'])
cursor.execute(add_record, data_record)
cnx.commit()
queue.task_done()
I decided to try MySQLdb and now it works fine. No idea what the problem was with MySQL connector