0

我正在尝试编写一个程序来查询数据库。数据库是 golfDB,它由一个名为 player 的表组成,其中包含 5 个字段:name(球员姓名)、totalGross(每轮总得分的总和)、totalRounds(打出的轮数)、pars(完成的总杆数) ,和小鸟(小鸟的总数。我的程序需要输出具有最多标准杆的球员,输入球员的平均得分(totalGross/totalRounds),并按照总得分从低到高的顺序列出球员. 现在我还没有真正研究具有最多 pars 函数或排序分数的函数的播放器。我的平均分数函数有问题。我收到这个错误,我真的不确定如何修理它:

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

1 回答 1

3

SQLite3 的fetchone返回一个元组,因此您需要在尝试潜水之前获取第一项,否则您实际上将划分两个元组。

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

在这种情况下,您的查询仅从一个字段获取数据,但请记住,查询可能返回不止一个字段,这就是 fetchone 返回元组的原因。

于 2013-04-24T14:14:09.577 回答