【问题标题】:Not getting data from database in python没有从python中的数据库获取数据
【发布时间】:2020-10-29 17:22:50
【问题描述】:

我尝试从程序在首次运行时创建的数据库中获取注册数据。

database.py

import sqlite3

CREATE_TABLE = """CREATE TABLE IF NOT EXISTS college (
                                    id INTEGER PRIMARY KEY,
                                    FirstName TEXT,
                                    SecondName TEXT,
                                    Position TEXT);"""

INSERT_DATA = "INSERT INTO college (FirstName, SecondName, Position) VALUES (?, ?, ?);"
DISPLAY_DATA = "SELECT * FROM college WHERE Position = ?;"
def connect():
    return sqlite3.connect('databas.db')

def create_table(connection):
    with connection:
        connection.execute(CREATE_TABLE)

def insert_data(connection, FirstName, SecondName, Position):
    with connection:
        connection.execute(INSERT_DATA, (FirstName, SecondName, Position))

def request_data(connection, position):
    with connection:
        return connection.execute(DISPLAY_DATA, (position,)).fetchall()

api.py

import database

API_MENU = """
--- Student Database ---

1) Register new student
2) Delete
3) Show students

4) Register new staff
5) Delete
6) Show staff

7) >> Quit the program

Your choice: """
def main():
    connection = database.connect()
    database.create_table(connection)

    
    while (choice := input(API_MENU)) != "7":
        if choice == "1":
            FirstName = "Julius"
            SecondName = "Jessie"
            Position = "Student"

            database.insert_data(connection, FirstName, SecondName, Position)
        elif choice == "2":
            database.request_data(connection, "Student")
        elif choice == "3":
            pass
        elif choice == "4":
            pass
        elif choice == "5":
            pass
        elif choice == "6":
            pass
        else:
            print("Invalid input, please try again!")

main()

使用选项 1 注册数据后,我根本没有收到任何数据。运行代码并选择选项 1 时,您应该输入姓名、姓氏和职位(学生/员工),然后将其写入数据库(为了将代码放在这里,我刚刚定义了字符串),然后选择选项 2 应该返回以“学生”为位置的数据,但它不返回任何数据。

【问题讨论】:

标签: python python-3.x database sqlite


【解决方案1】:

问题是我在实际使用函数 print() 来显示数据时疏忽了。

database.request_data(connection, "Student")

上面的行应该是:

print(database.request_data(connection, "Student"))

【讨论】:

    猜你喜欢
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-04-08
    • 2019-04-08
    • 2013-01-18
    • 2020-10-08
    • 2012-08-13
    • 1970-01-01
    相关资源
    最近更新 更多