MySQL返回的数据类型和python为不同的功能输出不同的类型 [英] MySQL returned datatype and python outputs different type for different functions

查看:182
本文介绍了MySQL返回的数据类型和python为不同的功能输出不同的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用MySQL返回值并将其输入到带有Python的Qt表中时遇到很多问题.我使用data = cursor.fetchall()

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

最初,我会把str()放在返回值周围,这适用于所有情况,除非当我在使用外语和日期时间遇到unicode问题时.所以现在我不把str()和外语插入到表中.但是,现在非字符串存在一些问题

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)我无法插入日期时间.当我执行type(data[i])时,它返回datetime,当我尝试使用data[i] = data[i].strftime("%Y-%m-%d %H:%M:%S")将其转换为字符串时,它告诉我'tuple' object does not support item assignment

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)所以我现在暂时通过了.现在,我尝试显示整数.我

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

这导致:

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

另外,如果我尝试这样做

additionally, if I try to do

print list(data[i])

它返回:

TypeError: 'long' object is not iterable

此外,

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

返回:

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

我必须从根本上丢失我的回报.是什么原因造成的?

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

推荐答案

您无法通过fetchall方法更改数据,因为它是一个元组而不是列表. 最简单的解决方法是:

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

这篇关于MySQL返回的数据类型和python为不同的功能输出不同的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆