查询sqlite3数据库



我想写一个程序来查询数据库。数据库是golfDB,它由一个名为players的表组成,表中有5个字段:name(球员的名字)、totalGross(每轮的总得分)、totalRounds(打过的回合数)、pars(打过的总杆数)和birdies(打过的总小鸟数)。我的程序需要输出获得最多杆数的玩家,输入玩家的平均得分(totalGross/totalRounds),并按照总得分从低到高的顺序列出玩家。现在,我还没有真正研究具有最多杆数函数或分数排序函数的玩家。我的平均分函数有问题。我得到这个错误,我真的不确定如何修复它:

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

SQLite3的fetchone返回一个元组,所以您需要在尝试跳水之前获得第一个项目,否则您实际上是在分割两个元组。

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

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

最新更新