Python中的一对多关系

时间:2015-07-27 22:56:07

标签: python sql database

嘿所以我对Python数据库很新,我想创建一个多对多的关系,以便能够使用它,但我遇到了一些能够在我的方法中插入和删除的问题。我有一个学生表,其中包含student_id,student_first和student_last。我有一个包含class_id,class_name和student_id的类表。我能够报告学生姓名和他们注册的课程,但我似乎无法弄清楚如何能够添加课程和删除课程。这是我下面的python代码。我有两个程序数据库和一个主程序。 (我的主要):

   import pymysql
    from project1database import *

    def dashes(size=80,char="-"):
        print(char*size)

    def nice_print(L):
        dashes(30,".")
        if len(L) == 0:
            print("There are no classes for this student")
        else:
            for x in L:
                print("++++>",x)
        dashes(30,".")

    db = database("project1")

    done = False
    dashes()
    print("Enter student id to select a name and show classes. Blank terminates")
    dashes()
    while not done:
        db.print_student()
        index = input("id -> ")
        if index.strip() =="":
            done=True
        else:
            index = eval(index)
            L=db.get_classes(index)
            nice_print(L)


    dashes()
    print("all done")
    dashes()
    db.close()

(我的数据库):

import pymysql
import sys

class database:

    con = ""
    name = ""
    dbname = ""
    last = 0

    def __init__(self,db_name): ## constructor
        try:
            self.con= pymysql.connect(host="localhost", user="root", passwd="", db=db_name)
        except pymysql.Error as e:
            print("Database Error [{:d}]: {:s}".format(e.args[0], e.args[1]))
            sys.exit(0)
        self.dbname = db_name

    def close(self):   
        self.con.close()

    def add(self,first,last):
        query = "insert into student(student _first,student_last) values ('{:s}','{:s}')".format(first,last)
        try:
            cur = self.con.cursor()
            cur.execute(query)
            self.last = cur.lastrowid
            self.con.commit()
        except pymysql.Error as e:
            print("Database Error [{:d}]: {:s}".format(e.args[0], e.args[1]))
            sys.exit(0)


    def delete(self,index):
        query = "delete from student where student_id = {:d}".format(index)
        cur = self.con.cursor()
        cur.execute(query)
        self.con.commit()

    def print_student(self):
        print("--- List of Student Names ---")
        query = """
           select student_id,student_first,student_last from student order by student_last
        """
        cur = self.con.cursor()
        cur.execute(query)
        row = cur.fetchone()

        while row is not None: 
            print("{:d}-> {:s}, {:s}".format(row[0],row[2],row[1]))
            row = cur.fetchone()

    def last_id(self):
        return self.last

    def get_classes(self,index):
        query = """
           select class_name from class where student_id = ? 
        """
        query = query.replace("?",str(index))
        cur = self.con.cursor()
        cur.execute(query)
        row = cur.fetchone()
        student_L=[]

        while row is not None:
            student_L.append(row[0])
            row = cur.fetchone()
        return student_L

0 个答案:

没有答案