繁体   English   中英

使用 Python 和 SQLite3 写入 a.txt 文件

[英]Writing to a .txt file using Python and SQLite3

我目前正在从事一个学校项目,我必须使用 Python、Tkinter 和 SQLite3 创建一个带有 GUI 的数据库应用程序。 我正在尝试创建一个 function ,用户将在其中将 OrderID 键入表单,并且将从数据库文件中获取具有相应 OrderID 的订单详细信息并插入到文本文件中。 我在尝试运行代码时收到以下错误:

  File "c:\Users\Ryan\OneDrive - C2k\A2 2020-2021\Computer Science\A2 Unit 5\Code\OrderForm.py", line 149, in PrintOrder
    write.write("-----CUSTOMER INVOICE-----", "\n".join(str(x) for x in results))
TypeError: write() takes exactly one argument (2 given)

我的代码片段和表单的屏幕截图附在下面:

    def PrintOrder(self):
        orderid = self.OrderIDEntry.get()
        productid = self.ProductIDEntry.get()
        quantity = self.QuantityEntry.get()
        with sqlite3.connect("LeeOpt.db") as db:
            cursor = db.cursor()
            search_order = ('''SELECT * FROM Orders WHERE OrderID = ?''')
            cursor.execute(search_order, [(orderid)])
            results = cursor.fetchall()

            if results:
                for i in results:
                    write = open("orderinvoice.txt","w")
                    write.write("-----CUSTOMER INVOICE-----", "\n".join(str(x) for x in results))
                    tkinter.messagebox.showinfo("Notification","Invoice generated successfully.")
                    self.ClearEntries()
            else:
                tkinter.messagebox.showerror("Error", "No order was found with this OrderID, please try again.")
                self.ClearEntries()

订单截图

您的问题/错误在于write.write("-----CUSTOMER INVOICE-----", "\n".join(str(x) for x in results))行。 write.write()中的逗号创建 2 个 arguments,其中 write-function 只需要一个(要写入的文本)。 我已经修改了您的代码,因此它仍然将所有结果写入单独的行。

def PrintOrder(self):
    orderid = self.OrderIDEntry.get()
    productid = self.ProductIDEntry.get()
    quantity = self.QuantityEntry.get()
    with sqlite3.connect("LeeOpt.db") as db:
        cursor = db.cursor()
        search_order = ('''SELECT * FROM Orders WHERE OrderID = ?''')
        cursor.execute(search_order, [(orderid)])
        results = cursor.fetchall()

        if results:
            for i in results:
                write = open("orderinvoice.txt","w")
                write.write("-----CUSTOMER INVOICE-----")
                for x in results:
                    write.write(str(x))
                tkinter.messagebox.showinfo("Notification","Invoice generated successfully.")
                self.ClearEntries()
        else:
            tkinter.messagebox.showerror("Error", "No order was found with this OrderID, please try again.")
            self.ClearEntries()

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM