سؤال

I am having plenty of problems with the MySQL returns and entering it into a Qt table with python. I use data = cursor.fetchall()

for data in data:
    for i in range(len(data)):
        sqlTableWidget.setItem(index,i,QtGui.QTableWidgetItem(data[i]))
    index = index +1

Originally I would put str() around the return, and that worked for everything except when i had unicode problems with foreign language and on the datetime. So now I dont put str() and the foreign language inserts to the table. However, there are some problems now with non strings

1) I cant insert datetime. When i do type(data[i]), it returns datetime and when I try to convert it to a string using data[i] = data[i].strftime("%Y-%m-%d %H:%M:%S") it tells me 'tuple' object does not support item assignment

2) So i just passed that for now. Now I try to get integers to display. I do

if data[i] == 1:
    print data[i]
    print type(data[i])
    data[i] = str(data[i])

this results in:

>>1
>>(type 'long')
>>Type Error: 'tuple' object does not support item assignment

additionally, if I try to do

print list(data[i])

it returns:

TypeError: 'long' object is not iterable

furthermore,

if data[i] is None:
    data[i] = 'No data'
sqlTableWidget.setItem(index,i,QtGui.QTableWidgetItem(data[i]))

returns:

QTableWidgetItem(QtableWidgetItem): argument 1 has unexpected type 'NoneType'

I must be missing something fundamentally about my returns. What causes this?

هل كانت مفيدة؟

المحلول

You cannot change the data from the fetchall method since it is a tuple and not a list. The easiest fix would be to do:

data = [list(i) for i in cursor.fetchall()]

نصائح أخرى

From your error log, I think problem happens because tuple in python doesn't support assignment.

Return values you fetch are ready-only tuple so it's invalid to change value directly on that.

In your code :

    data[i] = data[i].strftime("%Y-%m-%d %H:%M:%S")

Do you want to revise original data stored in DB directly? If not, you could use another variable with list type, like:

    my_list = data[i].strftime("%Y-%m-%d %H:%M:%S")
    // TODO MORE

Otherwise you may rely on update sentence to reivse data in DB.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top