繁体   English   中英

查询一个sqlite3数据库

[英]Querying a sqlite3 database

我正在尝试编写一个程序来查询数据库。 该数据库是golfDB,它由一个称为玩家的表组成,具有5个字段:名称(玩家的名字),totalGross(每个回合的总得分之和),totalRounds(打入的回合数),标准杆(标准杆总数) ,以及小鸟(小鸟总数)。我的程序需要输出标准杆最多的球员,输入球员的平均得分(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()

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM