0

i have small application written in tkinter, python. I would like to choose txt file by clicking button in tkinter and automaticaly send it to my SQL database. For this moment i have function responsible for choosing a file from my disc and printing my txt file in console:

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")

And function responsible for sending to SQL looks this way (txt file is inserted inside function):

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

Does anybody knows what could i do to connect those two functions? The idea is to choose txt file from function OpenFile() and then application should send it automatically to database.

1 Answer 1

2

Make Tabela take the file as a parameter instead of hard-coding pom1.txt, and call Tabela(UseFile) from OpenFile().

Also, since you're calling cursor.execute() with parameters, you shouldn't concatenate the elements of data into query, just put placeholders in the 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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.