Python从SQLite3数据库中检索信息

时间:2015-01-23 10:43:25

标签: python database sqlite

import sqlite3

Class = str(input("Which class are you in? A) 11A B) 11B C) 11C"))
f_name = str(input("What is your first name?"))
s_name = str(input("What is your surname?"))
h_score = "8"
a_score = "7"
t_taken = "3"

if Class == "11A" or "11a":
    counter = 0
    while counter < 1:
        db_students = sqlite3.connect('//persian/controlledassessment$/work/11 C CS/10BakeEd/Python/Task 2/db_Students.db')
        c=db_students.cursor()
        c.execute('''CREATE TABLE IF NOT EXISTS ClassA
         (student_firstname text,
        student_surname text,
        h_score number,
        a_score number,
        t_taken number,
        Class text)
        ''')
        c.execute('''INSERT INTO ClassA
         VALUES (?, ?, ?, ?, ?, ?)''',(f_name, s_name, h_score, a_score, t_taken, Class))
        db_students.commit()
        c.execute("SELECT * FROM ClassA")
        fetchall=c.fetchall() 
        print(fetchall)
        db_students.close()
        counter = counter + 1





elif Class == "11B" or "11b":
    print()

elif Class == "11C" or "11c":
    print()

else:    
    print("")

这是我目前的代码,其中的一些变量是占位符。我想要做的是从我创建的数据库中提取信息并将其分配给变量,以便我可以在平均值等计算中使用它们。

1 个答案:

答案 0 :(得分:0)

fetchall()返回一个行列表,其中每一行都是一个包含(在本例中)六个值的元组。

您可以浏览此列表,但除非您需要对所有行进行随机访问,否则最好将游标用作迭代器:

c.execute(...)
for row in c:
    print(c[0])    # prints all first names
else:
    pass           # no rows found

如果要计算平均值,最好直接在SQL中执行此操作:

c.execute("SELECT AVG(h_score), AVG(a_score) FROM ClassA WHERE Class LIKE '11a'")
avg_h, avg_a = c.fetch()