如何同时将数据从Excel工作表导入关系表

时间:2019-06-01 22:04:57

标签: python sqlite tkinter many-to-one

我正在尝试导入像图片一样的Excel工作表锁 excel sheet 进入3个具有1对多关系的表 像这些 the tables i want to import to 我可以按原样导入表格,但是这将是不正确的做法 请帮助我

我在堆栈溢出中寻找答案,但是我什么都没做 可能是我的坏问题

import tkinter as tk 
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
from tkinter import ttk
import sqlite3
import xlrd

class SchoolProjict(tk.Tk):
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        self.app_data = {"name": tk.StringVar(),
                         }
        container = tk.Frame(self)
        container.pack(side = "top", fill = "both", expand = True)
        container.grid_rowconfigure(0, weight = 1)
        container.grid_columnconfigure(0, weight = 1)
        self.frames = {}
        for F in (StartPage,  SetingPage):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row = 0, column = 0, sticky = "nsew")
        self.show_frame(StartPage)

    def show_frame(self, cont):
        frame = self.frames[cont]
        frame.tkraise()

    def get_page(self, classname):
        for page in self.frames.values():
            if str(page.__class__.__name__) == classname:
                return page
        return None

def printingstuff(var1):
    print (var1)

def printontherthing(page_class):
    print(page_class)


class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        self.controller = controller
        tk.Frame.__init__(self, parent)
        lablel = ttk.Label(self, text = "Main Page")
        lablel.pack(pady = 10, padx = 10)
        button2 = ttk.Button(self, text = "Siting", command = lambda: controller.show_frame(SetingPage))
        button2.pack()

class SetingPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        lablel = tk.Label(self, text = "Siting Page")
        lablel.grid(row = 0, column = 0)
        self.text1 = tk.Entry(self)  #<== i want to show the path of the file i am going to open Here after i select it from openfile 
        self.text1.grid(row = 2, column = 0)
        self.text1.focus()
        button1 = ttk.Button(self, text = "print text1", command = lambda: printingstuff(self.text1.get()))
        button1.grid(row = 3, column = 0)
        button2 = ttk.Button(self, text="open file", command= self.load_file, width=10)
        button2.grid(row = 3, column = 1)
        button4 = ttk.Button(self, text = "Main Page", command = lambda: controller.show_frame(StartPage))
        button4.grid(row = 4, column = 1)
        button4 = ttk.Button(self, text = "Creat Database", command = self.CreatTable)
        button4.grid(row = 4, column = 0)

    def load_file(self):
        fname = askopenfilename(filetypes=(("Excel file", "*.xls"),
                                           ("HTML files", "*.html;*.htm"),
                                           ("All files", "*.*") ))
        if fname:
            try:
                # print(fname)
                value = str(fname)
                page_var = self.controller.get_page("SetingPage")
                page_var.text1.insert(0, value)
                return

            except:                    
                showerror("Open Source File", "Failed to read file\n'%s'" % fname)
            return

    def CreatTable(self):
        loc = (self.text1.get())
        wb = xlrd.open_workbook(loc)
        sheet = wb.sheet_by_index(1)

        self.conn = sqlite3.connect("exeldata.db")
        self.cur = self.conn.cursor()
        self.wkb = wb
        self.sh = sheet

        self.cur.execute("""CREATE TABLE IF NOT EXISTS gradelevel(
            GlId INTEGER PRIMARY KEY,
            GradNumber text)""")

        self.cur.execute("""CREATE TABLE IF NOT EXISTS classnumber(
            CID INTEGER PRIMARY KEY,
            GradID INTEGER, 
            ClassNumber text,
            FOREIGN KEY(GradID) REFERENCES gradelevel(GlId))""")

        self.cur.execute("""CREATE TABLE IF NOT EXISTS studintinfo(
            StID INTEGER PRIMARY KEY,
            StudintID text,
            StudintName text,
            MobileNumber text,
            ClassID INTEGER,
            FOREIGN KEY(ClassID) REFERENCES classnumber(CID))""")

        print ("Table created")

        for sheet in wb.sheets():
            number_of_rows = sheet.nrows

        for r in  range(4, number_of_rows):    # <== this code good only for 1 tabl this dose not work with the 3 tables i did 
            mobile = self.sh.cell_value(r, 1)
            claasn = self.sh.cell_value(r, 2)   
            greadn = self.sh.cell_value(r, 3)
            studintn = self.sh.cell_value(r, 4)
            studinti = self.sh.cell_value(r, 5)

            self.cur.execute("INSERT INTO studint_for_insert(StudintID, StudintName, GradNumber1, ClassNumber1, MobileNumber)VALUES(?,?,?,?,?)",(studinti, studintn, greadn, claasn, mobile))

            self.conn.commit()
        print ("Data inserted")


        self.CloseConnection()

    def CloseConnection(self):
        self.cur.close()
        self.conn.close()
        print ("Connection Closed")

app = SchoolProjict()
app.mainloop()

我也是编程新手 谢谢大家的帮助

1 个答案:

答案 0 :(得分:0)

我在该网站的某些地方找到了答案 就像这样

self.cur.execute("SELECT GlId FROM gradelevel WHERE GradNumber = ? ", (greadn,)) 
            rows = self.cur.fetchone()
            if rows:
                GreadLvl_ID = rows[0] 
            else:
                self.cur.execute("INSERT INTO gradelevel(GradNumber)VALUES(?)",(greadn,))
                self.cur.execute("SELECT GlId FROM gradelevel WHERE GradNumber = ? ", (greadn,)) 
                rows = self.cur.fetchone()
                GreadLvl_ID = rows[0]
                greadID = self.cur.lastrowid


            self.cur.execute("SELECT CID FROM classnumber WHERE ClassNumb = ? AND GradID = ?", (claasn, GreadLvl_ID))
            rows1 = self.cur.fetchone()
            if rows1:
                class_ID = rows1[0]
            else:
                self.cur.execute("INSERT INTO classnumber(ClassNumb, GradID)VALUES(?,?)",(claasn, GreadLvl_ID))
                self.cur.execute("SELECT CID FROM classnumber WHERE ClassNumb = ? AND GradID = ?", (claasn, GreadLvl_ID))
                rows1 = self.cur.fetchone()
                class_ID = rows1[0]
                classnID = self.cur.lastrowid


            self.cur.execute("SELECT StID FROM studintinfo WHERE StudintID = ? AND ClassID = ?", (studinti, class_ID))
            rows2 = self.cur.fetchone()
            if rows2:
                studint_ID = rows2[0]
            else:
                self.cur.execute("INSERT INTO studintinfo(StudintID, StudintName, MobileNumber, ClassID)VALUES(?,?,?,?)",(studinti, studintn, mobile, class_ID))
                self.cur.execute("SELECT StID FROM studintinfo WHERE StudintID = ? AND ClassID = ?", (studinti, class_ID))
                rows2 = self.cur.fetchone()
                studint_ID = rows2[0]