2013-04-24 74 views
0

我想写一个程序来查询数据库。数据库是golfDB,它由一个名为玩家的表组成,其中包含5个字段:名称(玩家名称),totalGross(每轮总分数的总和),totalRounds(玩过的回合数),pars(制作的总数) ,小鸟(小鸟总数),我的程序需要输出最多的球员,一个输入球员的平均得分(totalGross/totalRounds),并按照总得分,从最低到最高排序。现在我还没有真正用过大多数语法分析功能或者函数来计算分数,我的平均分数函数有问题,我收到了这个错误,我真的不确定如何修复:查询一个sqlite3数据库

Traceback (most recent call last): 
    File "/Users/tinydancer9454/Documents/python/golfDBuserInterface.py", line 46, in <module> 
    main() 
    File "/Users/tinydancer9454/Documents/python/golfDBuserInterface.py", line 40, in main 
    queryDBavgScore(cursor) 
    File "/Users/tinydancer9454/Documents/python/golfDBuserInterface.py", line 29, in queryDBavgScore 
    answer = totalGrossScore/ totalRoundsScore 
TypeError: unsupported operand type(s) for /: 'tuple' and 'tuple' 

这是我到目前为止的代码:

import sqlite3 

def getDBCursor(DB): 
    """obtain and return a cursor for the database DB""" 
    conn= sqlite3.connect('/Users/tinydancer9454/Documents/python/golfDB') 
    cursor= conn.cursor() 
    return cursor 

def queryDBpars(cursor): 
    """find out which player had the most pars""" 
    cursor.execute('select name from players where pars >= 0') 


def queryDBavgScore(cursor): 
    """find the average score of inputed player""" 
    player= input("Please enter the player's name: ") 
    cursor.execute('select totalGross from players where name = ?', (player,)) 
    totalGrossScore = cursor.fetchone() 
    cursor.execute('select totalRounds from players where name = ?', (player,)) 
    totalRoundsScore = cursor.fetchone() 
    answer = totalGrossScore/ totalRoundsScore 
    print('The average score for', player, 'is', answer) 

def queryDBplayers(cursor): 
    """lists the players in order of their total gross score""" 


def main(): 
    """obtain cursor and query the database: golfDB""" 
    cursor= getDBCursor('golfDB') 
    queryDBpars(cursor) 
    queryDBavgScore(cursor) 
    queryDBplayers(cursor) 
    cursor.close() 

回答

3

的SQLite3的fetchone返回一个元组,所以你需要尝试潜入之前得到的第一个项目,否则你就基本上可以划分两个元。

totalGrossScore = cursor.fetchone()[0] 
totalRoundsScore = cursor.fetchone()[0] 

在这种情况下,你的查询只从一个字段获取数据,但请记住,一个查询可能返回不止一个领域,这就是为什么fetchone返回一个元组。

+1

是的,这是正确的。因为即使您只取一行,它仍可能包含多个数据字段;例如编号,名称等 – eandersson 2013-04-24 14:17:12

+0

好的,这使得更多的意义。谢谢。 – tinydancer9454 2013-04-24 14:19:48

+0

不用担心@ tinydancer9454。很高兴我能帮上忙。 – eandersson 2013-04-24 14:25:25