简体   繁体   中英

Python/MySQL - import csv file to mysql

I am developing an application that consists of selecting a file (.csv) in a directory and importing the data into it into the database (mysql), but the following error is appearing:

Traceback (most recent call last):
  File "C:\Users\TESTES\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:/Users/TESTES/PycharmProjects/Heiken/tess.py", line 16, in import_file
    with open(browse_file):
TypeError: expected str, bytes or os.PathLike object, not function

Below is the complete code with the functions, in a testing interface:

from tkinter import *
import pymysql
from tkinter import filedialog

tess = Tk()

def browse_file():

    fname = filedialog.askopenfilename(filetypes=(("Template files", "*.csv"), ("All files", "*")))
    print(fname)

def import_file():
    conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='omnia')
    print('connect successfull!')

    with open(browse_file):
        statm = "INSERT INTO omniacademp(n_id, n_cod, c_cnpjcpf, c_razao, c_enderecom, c_nr, c_compl, c_cep, c_bairro, c_cidade, c_estado, c_telefone, c_email, c_celular, c_email2) VALUES (0, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        cursor = conn.cursor()
        cursor.execute(statm)
        conn.commit()



bt = Button(tess, text='browse file', command=browse_file)
bt.place(x=10, y=10)

bt = Button(tess, text='import file', command=import_file)
bt.place(x=10, y=45)


tess.mainloop()

First , you should return path from browse_file function. Try this :

from tkinter import *
import pymysql
from tkinter import filedialog

tess = Tk()

def browse_file():
    return filedialog.askopenfilename(filetypes=(("Template files", "*.csv"), ("All files", "*")))

def import_file():
    conn = pymysql.connect(host='localhost', port=3306, user='root', password='', db='omnia')
    print('connect successfull!')

    with open(browse_file()):
        statm = "INSERT INTO omniacademp(n_id, n_cod, c_cnpjcpf, c_razao, c_enderecom, c_nr, c_compl, c_cep, c_bairro, c_cidade, c_estado, c_telefone, c_email, c_celular, c_email2) VALUES (0, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        cursor = conn.cursor()
        cursor.execute(statm)
        conn.commit()



bt = Button(tess, text='browse file', command=browse_file)
bt.place(x=10, y=10)

bt = Button(tess, text='import file', command=import_file)
bt.place(x=10, y=45)


tess.mainloop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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