【问题标题】:Database - The ID does not run continuously数据库 - ID 不连续运行
【发布时间】:2021-12-22 15:44:44
【问题描述】:

谁能告诉我为什么ID没有在数据库中连续运行。

我正在将 Python 程序中的数据(使用我在 TKinter 中构建的 GUI)写入 MariaDB。我使用 HeidiSQL 查看数据。我注意到 ID 不是连续运行而是有跳跃。 ID 列设置为 auto_increment。

Screenshot Database ID

和我的同事谈过之后,ID 是唯一的还不够,它还必须是连续的。

似乎只有当我调用该函数将数据从 Excel 文件复制到数据库时才会出现此问题。我用不同数量的数据再次对其进行了测试,并且 ID 与 Excel 中的行数完全相同。举个例子:如果Excel中有8行数据,那么ID会跳8位。

1
2
3
4
5
6
7
8
16
to
24
32
to
40

感谢您的帮助。

这是函数的代码:

    # create window to open excel files
    def openexcel():
        # ---------- Display Settings ---------------
        root_openexcel = tk.Tk()
        root_openexcel.title("Open Excel")
        # root_tgadisp.geometry("370x680")

        root_openexcel.geometry("650x650")  # set the root_openexcel dimensions
        # root_openexcel.pack_propagate(False)  # tells the root_openexcel to not let the widgets inside it determine its size.
        # root_openexcel.resizable(0, 0)  # makes the root_openexcel window fixed in size.

        # Frame for TreeView
        frame1 = tk.LabelFrame(root_openexcel, text="Excel Data")
        frame1.place(height=500, width=600, relx=0.01)

        # Frame for open file dialog
        file_frame = tk.LabelFrame(root_openexcel, text="Open File")
        file_frame.place(height=100, width=600, rely=0.78, relx=0.01)

        # Buttons
        button1 = tk.Button(file_frame, text="Browse A File", command=lambda: File_dialog())
        button1.place(rely=0.65, relx=0.50)

        button2 = tk.Button(file_frame, text="Load File", command=lambda: Load_excel_data())
        button2.place(rely=0.65, relx=0.30)

        button3 = tk.Button(file_frame, text="Load into Database", command=lambda: Load_into_database())
        button3.place(rely=0.65, relx=0.70)

        # The file/file path text
        label_file = ttk.Label(file_frame, text="No File Selected")
        label_file.place(rely=0, relx=0)

        ## Treeview Widget
        tv1 = ttk.Treeview(frame1)
        tv1.place(relheight=1, relwidth=1)  # set the height and width of the widget to 100% of its container (frame1).

        treescrolly = tk.Scrollbar(frame1, orient="vertical",
                                   command=tv1.yview)  # command means update the yaxis view of the widget
        treescrollx = tk.Scrollbar(frame1, orient="horizontal",
                                   command=tv1.xview)  # command means update the xaxis view of the widget
        tv1.configure(xscrollcommand=treescrollx.set,
                      yscrollcommand=treescrolly.set)  # assign the scrollbars to the Treeview Widget
        treescrollx.pack(side="bottom", fill="x")  # make the scrollbar fill the x axis of the Treeview widget
        treescrolly.pack(side="right", fill="y")  # make the scrollbar fill the y axis of the Treeview widget


        def File_dialog():
            """This Function will open the file explorer and assign the chosen file path to label_file"""
            filename = filedialog.askopenfilename(initialdir="C:/Users/Zlatan/Desktop/Project_PolymerSQL",
                                                  title="Select A File",
                                                  filetype=(("xlsx files", "*.xlsx"), ("All Files", "*.*")))
            label_file["text"] = filename
            return None

        def Load_excel_data():
            """If the file selected is valid this will load the file into the Treeview"""
            file_path = label_file["text"]
            try:
                excel_filename = r"{}".format(file_path)
                if excel_filename[-4:] == ".csv":
                    df = pd.read_csv(excel_filename)
                else:
                    df = pd.read_excel(excel_filename)

            except ValueError:
                tk.messagebox.showerror("Information", "The file you have chosen is invalid")
                return None
            except FileNotFoundError:
                tk.messagebox.showerror("Information", f"No such file as {file_path}")
                return None

            clear_data()
            tv1["column"] = list(df.columns)
            tv1["show"] = "headings"
            for column in tv1["columns"]:
                tv1.heading(column, text=column)  # let the column heading = column name

            df_rows = df.to_numpy().tolist()  # turns the dataframe into a list of lists
            for row in df_rows:
                tv1.insert("", "end",
                           values=row)  
            return None

        def Load_into_database():
            file_path = label_file["text"]
            try:
                excel_filename = r"{}".format(file_path)
                if excel_filename[-4:] == ".csv":
                    df = pd.read_csv(excel_filename, header=None, names=['Lagerzeit', 'Lager_Temperatur', 'Lager_Medium', 'Datum_Prüfung', 'Order_name', 'Operator_name', 'Sample', 'Strain', 'F_s', 'F_0', 'sigma_s', 'sigma_0', 'A', 'alpha', 'Wert_1', 'Wert_2', 'Wert_3', 'Wert_4'])
                else:
                    df = pd.read_excel(excel_filename, header=None, names=['Lagerzeit', 'Lager_Temperatur', 'Lager_Medium', 'Datum_Prüfung', 'Order_name', 'Operator_name', 'Sample', 'Strain', 'F_s', 'F_0', 'sigma_s', 'sigma_0', 'A', 'alpha', 'Wert_1', 'Wert_2', 'Wert_3', 'Wert_4'])

            except ValueError:
                tk.messagebox.showerror("Information", "The file you have chosen is invalid")
                return None
            except FileNotFoundError:
                tk.messagebox.showerror("Information", f"No such file as {file_path}")
                return None

            engine = create_engine("mariadb+mariadbconnector://root:pwd@127.0.0.1:3306/polymer")
            df.to_sql('tssr', con=engine, if_exists='append', index=False)

        #clear function in openexcel
        def clear_data():
            tv1.delete(*tv1.get_children())
            return None

【问题讨论】:

  • 你能用更少的代码重现这个问题吗? :)
  • 如果事务有问题并进行回滚,预计数据库会在此工作。问题是如果您保存的数据不存在

标签: python sql excel tkinter mariadb


【解决方案1】:

没关系。 ID 的主要特点是它必须是唯一的,而不是严格的顺序。

ID 不应该是连续的,尽管 MariaDB 的子句 AUTO_INCREMENT 暗示相反。

数据库将 ID 视为唯一标识行的内部值。它们不会暴露在 UI 或外部接口上。无需关心它的连续性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-02
    • 2013-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多