简体   繁体   English

Python:如何查询以从 sqlite3 表中提取数据?

[英]Python: How do I query to pull data from sqlite3 table?

I'm trying to get my code to work but I keep getting this error.我正在尝试让我的代码正常工作,但我不断收到此错误。

File "C:\Users\mikae\Desktop\Sem 9\CSE115\Assignment 2\Actual\A2 (Version 5).py", line 186, in main print_table_bookings(conn,booking_data[i])文件“C:\Users\mikae\Desktop\Sem 9\CSE115\Assignment 2\Actual\A2 (Version 5).py”,第 186 行,在主 print_table_bookings(conn,booking_data[i])

IndexError: list index out of range IndexError:列表索引超出范围

Currently, this is my code.目前,这是我的代码。 I'm not done with it, but I'm trying to write out two queries:我还没有完成它,但我正在尝试写出两个查询:

  1. Find all the bookings of a specific trainer查找特定培训师的所有预订
  2. Find the gender of the trainer for a type of training.找到一种培训类型的培训师的性别。

在此处输入图像描述

I've tried a lot of variations but I just can't get the logic down.我尝试了很多变化,但我就是无法理解逻辑。 I would appreciate feedback and any help that I can get.我将不胜感激反馈和任何我能得到的帮助。

Code代码

import sqlite3
from sqlite3 import Error
import os

# Create a connection to the SQLite database via DB file.
def create_connection(db_file):
    """create a database connection to the SQLite database
    specified by db_file
    :param db_file:database file
    :return:Connection object or None
    """
    
    conn = None
    try:
        conn = sqlite3.connect(db_file)
        return conn
    except Error as e:
        print(e)
    return conn


# Create tables from SQL statement
def create_table(conn,create_table_sql):
    """create a table from the create_table_sql statement
    :param conn:Connection object
    :param create_table_sql:a CREATE TABLE statement
    :return:
    """

    try:
        c = conn.cursor()
        c.execute(create_table_sql)
    except Error as e:
        print(e)
    
# Bookings Table
def print_table_bookings(conn, bookings):
    sql=""" INSERT INTO bookings (booking_id,trainer_id,training_id,session_date,session_slot)
    VALUES (?,?,?,?,?)"""
    c = conn.cursor()
    c.execute(sql,bookings)
    conn.commit()
    return c.lastrowid

# Trainers Table
def print_table_trainers(conn, trainers):
    sql=""" INSERT INTO trainers (trainer_id,name,gender,mobile,specialisation,rate)
    VALUES (?,?,?,?,?,?)"""
    c = conn.cursor()
    c.execute(sql,trainers)
    conn.commit()
    return c.lastrowid

# Trainings Table
def print_table_trainings(conn, trainings):
    sql=""" INSERT INTO trainings (training_id,description,duration)
    VALUES (?,?,?)"""
    c=conn.cursor()
    c.execute(sql,trainings)
    conn.commit()
    return c.lastrowid

# Print Tables
# Print Bookings
def display_bookings(conn):
    c=conn.cursor()
    c.execute("SELECT * FROM bookings")
    rows=c.fetchall()
    for row in rows:
        print(row)
        print("\n") 
        
# Print Bookings
def display_trainers(conn):
    c=conn.cursor()
    c.execute("SELECT * FROM trainers")
    rows=c.fetchall()
    for row in rows:
        print(row)
        print("\n")
        
# Print Bookings
def display_trainings(conn):
    c=conn.cursor()
    c.execute("SELECT * FROM trainings")
    rows=c.fetchall()
    for row in rows:
        print(row)
        print("\n")
        
# Query to display Trainer's bookings by Trainer's Name
# NOT DONE

# Main Code
def main():
    database = os.path.abspath(os.getcwd()) + "\healthhub.db"

    # Create Bookings Table
    sql_create_bookings_table = """CREATE TABLE IF NOT EXISTS bookings (
                                booking_id INTEGER PRIMARY KEY,
                                trainer_id INTEGER NOT NULL,
                                training_id TEXT,
                                session_date INTEGER NOT NULL,
                                session_slot TEXT NOT NULL,
                                FOREIGN KEY(trainer_id) REFERENCES trainer(id),
                                FOREIGN KEY(training_id) REFERENCES training(id)
                                );"""

    # Create Trainer Table
    sql_create_trainers_table = """CREATE TABLE IF NOT EXISTS trainers (
                                trainer_id INTEGER PRIMARY KEY,
                                name TEXT NOT NULL,
                                gender TEXT NOT NULL,
                                mobile TEXT NOT NULL,
                                specialisation TEXT NOT NULL,
                                rate INTEGER NOT NULL
                                );"""

    # Create Trainings Table
    sql_create_trainings_table = """CREATE TABLE IF NOT EXISTS trainings (
                                training_id INTEGER PRIMARY KEY,
                                description TEXT NOT NULL,
                                duration INTEGER NOT NULL
                                );"""

    # Create a Database(DB) Connection
    conn = create_connection(database)

    # Create Tables using def above
    if conn is not None: 
        create_table(conn,sql_create_bookings_table)
        create_table(conn,sql_create_trainers_table)
        create_table(conn,sql_create_trainings_table)

        with conn:
            # Error prevention
            c=conn.cursor()
            c.execute("DELETE FROM bookings;");
            c.execute("DELETE FROM trainers;");
            c.execute("DELETE FROM trainings;");

            # Populating the tables
            # Bookings table
            booking_1 = (101,'001','0001','01082021','Morning')
            booking_2 = (102,'001','0001','01082021','Morning')
            booking_3 = (103,'001','0001','01082021','Morning')
            booking_4 = (104,'001','0001','01082021','Morning')
            booking_5 = (105,'001','0001','01082021','Morning')
            booking_6 = (106,'001','0001','01082021','Morning')
            booking_7 = (107,'001','0001','01082021','Morning')
            booking_8 = (108,'001','0001','01082021','Morning')
            booking_9 = (109,'001','0001','01082021','Morning')
            booking_10 = (110,'001','0001','01082021','Morning')

            # Trainers Table
            trainer_1 = (2021,'Gary','Male','91234567','Weight Loss','85')
            trainer_2 = (2022,'Bary','Male','91234568','Weight Loss','185')
            trainer_3 = (2023,'Mary','Female','91234569','Weight Loss','85')
            trainer_4 = (2024,'Stephanie','Female','91234570','Weight Loss','85')
            trainer_5 = (2025,'Austin','Male','91234571','Weight Loss','65')
            trainer_6 = (2026,'Tynia','Female','91234572','Weight Loss','85')
            trainer_7 = (2027,'Oswald','Male','91234573','Weight Loss','55')
            trainer_8 = (2028,'Aria','Female','91234574','Weight Loss','45')
            trainer_9 = (2029,'Micheal','Male','91234575','Weight Loss','95')
            trainer_10 = (2030,'Lily','Female','91234576','Weight Loss','105')


            #trainings table
            trainings_1 = (3031,'Weight Loss','90')
            trainings_2 = (3032,'Cardio','90')
            trainings_3 = (3033,'Boxing','90')
            trainings_4 = (3034,'Kickboxing','90')
            trainings_5 = (3035,'Muay Thai','90')
            trainings_6 = (3036,'Kettlebells','90')
            trainings_7 = (3037,'Strength training','90')
            trainings_8 = (3038,'Yoga','90')
            trainings_9 = (3039,'Sparring','90')
            trainings_10 = (3040,'Jiu-jitsu','90')

            #Loop to write data into table
            booking_data = [booking_1,booking_2,booking_3,booking_4,booking_5,booking_6,booking_7,booking_8,booking_9,booking_10]
            trainer_data = [trainer_1,trainer_2,trainer_3,trainer_4,trainer_5,trainer_6,trainer_7,trainer_8,trainer_9,trainer_10]
            training_data =  [trainings_1,trainings_2,trainings_3,trainings_4,trainings_5,trainings_6,trainings_7,trainings_8,trainings_9,trainings_10]
            i=0
            while i < 20:
                print_table_bookings(conn,booking_data[i])
                print_table_trainers(conn,trainer_data[i])
                print_table_trainings(conn,training_data[i])
                i=i+1 
            
            
            #Displaying Table
            print_table_bookings(conn)
            print()
            print_table_trainers(conn)
            print()
            print_table_trainings(conn)
            print()
                
            
if __name__=='__main__':
    main()

here:这里:

booking_1 = (101,'001','0001','01082021','Morning')

...

booking_data = [booking_1,booking_2,booking_3,booking_4,booking_5,booking_6,booking_7,booking_8,booking_9,booking_10]

...

create_table(conn,booking_data[i])

the booking_data[i] will never be a string containing a SQL instruction. booking_data[i]永远不会是包含 SQL 指令的字符串。 Here you probably want to transform this tuple into a INSERT statement before you execute it.在这里,您可能希望在执行此元组之前将其转换为 INSERT 语句。

In main() after you create the tables, you are trying to insert new rows with this loop:在创建表后的main()中,您尝试使用此循环插入新行:

i=0
while i < 20:
    create_table(conn,booking_data[i])
    create_table(conn,trainer_data[i])
    create_table(conn,training_data[i])
    i=i+1 

in which you use create_table() instead of print_table_bookings() , print_table_trainers() and print_table_trainings() .在其中使用create_table()而不是print_table_bookings()print_table_trainers()print_table_trainings()

Change to this:改成这样:

i=0
while i < 20:
    print_table_bookings(conn,booking_data[i])
    print_table_trainers(conn,trainer_data[i])
    print_table_trainings(conn,training_data[i])
    i=i+1 

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

相关问题 如何使用我的 sqlite3 数据库中的表数据作为 python 变量 - How do i use table data from my sqlite3 database as a python variable 如何使用Python查询sqlite3中的unicode字符串 - how do I query an unicode string in sqlite3, using Python 我如何在 python 中转储单个 sqlite3 表? - how do i dump a single sqlite3 table in python? 如何使用python在SQLite3中显示表结构? - How do I display the table structure in SQLite3 with python? 如何使用python从SQlite3数据库查看特定表? - How do I view a specific table from a SQlite3 databse using python? 如何从SQLite3表中获取数据作为浮点数? 它以元组形式返回 - how do i get data from SQLite3 table as a float? it is being returned as a tuple 如何将数据写入从Python中的SQL数据库获取的文件中? (sqlite3的) - How do I write data to a file that I have taken from an SQL database in Python? (sqlite3) 如何使用 SQLite3 和 Python 更新 SQLite 表中的行 - How to do update rows in SQLite table using SQLite3 and Python python sqlite3 tkinter-如何为sqlite表中的每一行自动创建新的小部件? - python sqlite3 tkinter- How do I automatically create new widgets for every row in an sqlite table? 使用python中tkinter下拉菜单中的数据更新sqlite3表 - Updating sqlite3 table with data from tkinter dropdown menu in python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM