天天看點

python和mysql資料類型對應,MySQL傳回的資料類型和python為不同的功能輸出不同的類型...

python和mysql資料類型對應,MySQL傳回的資料類型和python為不同的功能輸出不同的類型...

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