如何从SQL数据库中获取数据? (故障排除)

时间:2014-04-08 01:25:07

标签: python sqlite

我使用SQLite查询创建了表格,如下所示:

import sqlite3 as lite
import sys

con = lite.connect('Records.db')

with con:
    cur = con.cursor()    
    cur.execute("CREATE TABLE Users(User_Id INTEGER PRIMARY KEY, Username STRING, Password STRING, Acc_Type STRING, First_Name STRING, Surname STRING, Class STRING, FullName STRING)")
    cur.execute("INSERT INTO Users VALUES(1, 'Admin', 'PassWord567', 'Admin', '', 'Admin', 'None', 'Admin')")
    cur.execute("INSERT INTO Users VALUES(2, 'HamzahA12', 'password', 'Student', 'Hamzah', 'Akhtar', '13E2', 'Hamzah Akhtar')")
    cur.execute("CREATE TABLE Questions(Question_Id INTEGER PRIMARY KEY, Question STRING, Answer STRING, Mark INTEGER, Topic STRING, Incorrect STRING, QType STRING)")
    cur.execute("INSERT INTO Questions VALUES(1, 'What is 2/3 of 6?', '4', '1', 'Fractions', 'None', 'Numerical')")
    cur.execute("INSERT INTO Questions VALUES(2, 'What is 5/4 of 20?', '25', '1', 'Fractions', 'None', 'Numerical')")
    cur.execute("CREATE TABLE Tests(Test_Id INTEGER PRIMARY KEY, TestName STRING, TotalMarks INTEGER, Calculator STRING)")
    cur.execute("INSERT INTO Tests(TestName) VALUES('Test 1')")
    cur.execute("INSERT INTO Tests(TestName) VALUES('Test 2')")

但是,在获取数据时,出于某种原因,我可以从User表或Question表中获取数据,但无法从Test表中获取数据。我使用以下代码从表中获取数据:

con = lite.connect('Records.db')
            with con:
                cur = con.cursor()
                cur.execute("SELECT TestName FROM Tests")
                rows = cur.fetchall()
                for row in rows:
                    Testname = str(row)
                    Testname = Testname[2:-3]
                    print(Testname)

在我的获取数据的代码中,我使用[2:-3]从提取的数据中删除撇号和括号。 出于某种原因,在获取时,它返回[]。关于我做错什么的任何想法?顺便说一下,当使用相同的方法(包括[2:-3])从问题表或用户表等其他表中获取数据时,没有问题...... ???

2 个答案:

答案 0 :(得分:0)

row列表转换为字符串,然后删除该转换生成的标点符号,是一种非常人为的提取值的方法。

直接从行中提取值:

for row in rows:
    testname = row[0]
    ...

答案 1 :(得分:0)

我使用以下方法解决了我的问题:(已插入Test_Id TestName

cur.execute("CREATE TABLE Tests(Test_Id INTEGER PRIMARY KEY, TestName STRING, TotalMarks INTEGER, Calculator STRING)")
cur.execute("INSERT INTO Tests(Test_Id, TestName) VALUES(1, 'Test 1')")
cur.execute("INSERT INTO Tests(Test_Id, TestName) VALUES(1, 'Test 2')")