为了账号安全,请及时绑定邮箱和手机立即绑定

在python中的其他函数中插入函数

在python中的其他函数中插入函数

www说 2022-07-12 09:48:07
我有用 tkinter、python 编写的小应用程序。我想通过单击 tkinter 中的按钮来选择 txt 文件并自动将其发送到我的 SQL 数据库。此刻,我有负责从我的光盘中选择一个文件并在控制台中打印我的 txt 文件的功能:def OpenFile():    name = askopenfilename(initialdir="",                       filetypes =(("Text File", "*.txt"),("All Files","*.*")),                       title = "Choose a file."                       )    print(name)    #Using try in case user types in unknown file or closes without choosing a file.    try:        with open(name,'r') as UseFile:            print(UseFile.read())    except:        print("No file exists")负责发送到 SQL 的函数看起来是这样的(txt 文件插入函数内部):def Tabela():    with open("pom1.txt") as infile:        for line in infile:            data = line.split("\t")            print(data)            query = ("INSERT INTO Pomiary_Obwod_90(Pomiar_x, Pomiar_y, Pomiar_z) VALUES"                 "(" + data[1] + ", " + data[2] + ", " + data[3] + ");")            cursor.execute(query, data)            con.commit()   return有谁知道我可以做些什么来连接这两个功能?这个想法是从函数 OpenFile() 中选择 txt 文件,然后应用程序应自动将其发送到数据库。
查看完整描述

1 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

将Tabela文件作为参数而不是硬编码pom1.txt,并Tabela(UseFile)从OpenFile().


此外,由于您cursor.execute()使用参数调用,因此不应连接datainto的元素query,只需在查询中放置占位符。


def OpenFile():

    name = askopenfilename(initialdir="",

                       filetypes =(("Text File", "*.txt"),("All Files","*.*")),

                       title = "Choose a file."

                       )

    print(name)

    #Using try in case user types in unknown file or closes without choosing a file.

    try:

        with open(name,'r') as UseFile:

            Tabela(UseFile)

    except:

        print("No file exists")



def Tabela(infile):

    for line in infile:

        data = line.strip().split("\t")

        print(data)

        query = ("INSERT INTO Pomiary_Obwod_90(Pomiar_x, Pomiar_y, Pomiar_z) VALUES (%s, %s, %s)")

        cursor.execute(query, data)

        con.commit()

   return


查看完整回答
反对 回复 2022-07-12
  • 1 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号