Python Forum
Write to db Table - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Write to db Table (/thread-4377.html)



Write to db Table - VodkaSodaWater - Aug-11-2017

Hi All,
I am getting an exit code 1 but I am not getting a reason why or an error. Im running version 2.7.13, and making an API call. I can make the API call no problem, and I can copy out everything and just connect to the db, which works fine. Its the combination of both is where I am getting tripped up. I even made a table of just varchar and changed all the returned data to str to rule out any datatype errors. I have switched the cursor.execute order as well which produced an error so I put it back to the way it is. Can anyone suggest what I might need to do to get this to write to my table?

import httplib
import json
import datetime
import mysql.connector as mariadb

cnx = mariadb.connect(user='root', password='pw', host='127.0.0.1', database='apidata')
cursor = cnx.cursor()
whenInserted = datetime.datetime.now()

add_Data = ("INSERT INTO runningprocesses "
            "(Id, App, start_time, process, cpu, mem_percent, cpu_time, can_restart, whenInserted) "
            "VALUES (%(Id)s, %(App)s, %(start_time)s, %(process)s, %(cpu)s, %(mem_percent)s, %(cpu_time)s, %(can_restart)s, %(whenInserted)s)")

headers = {'Accept': 'application/json', 'Authorization': 'apikey=#########'}
conn = httplib.HTTPSConnection('server.com')
conn.request('GET', '/api/v1/data/processes', headers=headers)

item = conn.getresponse()
resp_str = item.read().decode('utf-8')
resp_Data = json.loads(resp_str)

for data in resp_Data:
    print "Server01"
    print str(data["start_time"])
    print str(data["process"])
    print str(data["cpu"])
    print str(data["mem_percent"])
    print str(data["cpu_time"])
    print str(data["can_restart"])

cursor.execute(resp_Data, add_Data)
Id = cursor.lastrowid

cnx.commit()
cursor.close()
cnx.close()

Tried Idle and now getting this error. Any ideas as to how to solve this?
File "C:\Python27\lib\site-packages\mysql\connector\cursor.py", line 536, in execute
stmt = operation.encode(self._connection.python_charset)
AttributeError: 'list' object has no attribute 'encode'


RE: Write to db Table - hbknjr - Aug-12-2017

Somewhere in your code, list object is passed instead of a string. Try an IDE to debug.
eg-

>>> mylist = ['mystring']
>>> mylist.encode('utf-8')
You'll get-

Error:
Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'list' object has no attribute 'encode'

Instead you have to pass the string contained in the list.


>>> mylist[0].encode('utf-8')  // first element of List
Output:
b'mystring'