查询sqlite3数据库

时间:2013-04-24 14:12:28

标签: python database sqlite

我正在尝试编写一个程序来查询数据库。数据库是golfDB,它包含一个名为player的表,其中包含5个字段:name(玩家姓名),totalGross(每轮总得分的总和),totalRounds(播放的轮数),pars(制作的总数)和小鸟(小鸟队的总数。我的节目需要输出一个输入最多的球员,一个输入球员的平均分数(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()

1 个答案:

答案 0 :(得分:3)

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

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

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