MySQL returned datatype and python outputs different type for different functions

你。 提交于 2019-12-25 02:20:29

问题


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?


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/23210847/mysql-returned-datatype-and-python-outputs-different-type-for-different-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!