mysq的数据类型

2024-10-01 00:16:49 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是我用Python编写的代码:

queryuniq = "SELECT COUNT(distinct src_ip), COUNT(distinct video_id)FROM video"
cur.execute(queryuniq)
uniq = []
uniq = cur.fetchall()
print uniq
ip = str(uniq[0])
video = str(uniq[1])
fd2.write("There are %d ip addresses and %d video in total" %(int(ip), int(video)))

这是我得到的“uniq”变量的值:

^{pr2}$

这个错误消息:

 fd2.write("There are %d ip addresses in total" %(int(ip)))
 ValueError: invalid literal for int() with base 10: '((2052L,),)'
 video = str(uniq[1])
 IndexError: tuple index out of range

我只想计算数据库中列中的不同项,并在文件中打印INT值。在

有人能解释一下为什么SELECT命令返回一个奇怪的数据格式,比如((2052L,163581L),)?不明白为什么数字后面有个“L”。。在

我怎样才能解决这个问题?非常感谢!在


Tags: ipaddressesvideocountselectarewriteint
2条回答

你的代码有几处错误。在

首先,cur.fetchall()(顾名思义)从查询中获取所有结果。由于Python不知道查询只返回一行,所以它仍然返回所有行的元组。因此uniq[0]不引用行中的第一个字段,而是引用结果中的第一行。在

因为您知道您只需要一行,所以可以使用cur.fetchone()。在

其次,为什么要将结果转换成字符串,然后再转换回int?那似乎毫无意义。它们已经是正确的格式-L只表示它们是“long int”。在

uniq是元组的元组(外部级别的每个条目表示一个数据库,其中有一个列值的元组)。在

查询始终返回一行。因此,外部元组始终包含一个元素,您可以通过替换来修复代码:

uniq = cur.fetchall()

^{pr2}$

另外,从int到string再到int的转换是不必要的。在

总而言之,以下是代码的整理版本:

queryuniq = "SELECT COUNT(distinct src_ip), COUNT(distinct video_id)FROM video"
cur.execute(queryuniq)
uniq = cur.fetchall()[0]
ip, video = uniq
fd2.write("There are %d ip addresses and %d video in total" %(ip, video))

相关问题 更多 >