2011-12-09 32 views
1

这是我在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的” 可变我得到的值:

((2052L, 163581L),) 

而且此错误消息:

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”..

我该如何解决这个问题?非常感谢!

+0

检查表中的数据,最有可能它包含奇怪格式的数据? –

回答

2

uniq是元组的元组(在外侧电平中的每个条目表示数据库,其内有列的元组值)。

您查询总是返回一行。因此,外元组总是包含一个元素,你可以通过更换修复代码:

uniq = cur.fetchall() 

uniq = cur.fetchall()[0] 

另外,从int到字符串中的转换,然后回到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)) 
2

有几件事情你的代码错误。首先,cur.fetchall() - 顾名思义 - 从查询中获取所有结果。由于Python不知道你的查询只返回一行,它仍然返回所有行的元组。因此uniq[0]不引用行中的第一个字段,它引用结果中的第一行。

既然你知道你只想要一行,你可以使用cur.fetchone()

其次,为什么你将结果转换为字符串,然后将它们转换回整数?这似乎毫无意义。它们的格式正确 - L意味着它们是“长整数”。