下面是我用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”。。在
我怎样才能解决这个问题?非常感谢!在
你的代码有几处错误。在
首先,
cur.fetchall()
(顾名思义)从查询中获取所有结果。由于Python不知道查询只返回一行,所以它仍然返回所有行的元组。因此uniq[0]
不引用行中的第一个字段,而是引用结果中的第一行。在因为您知道您只需要一行,所以可以使用
cur.fetchone()
。在其次,为什么要将结果转换成字符串,然后再转换回int?那似乎毫无意义。它们已经是正确的格式-
L
只表示它们是“long int”。在uniq
是元组的元组(外部级别的每个条目表示一个数据库行,其中有一个列值的元组)。在查询始终返回一行。因此,外部元组始终包含一个元素,您可以通过替换来修复代码:
与
^{pr2}$另外,从int到string再到int的转换是不必要的。在
总而言之,以下是代码的整理版本:
相关问题 更多 >
编程相关推荐