gpt4 book ai didi

Python/MySQL - 将csv文件导入mysql

转载 作者:行者123 更新时间:2023-11-29 09:25:05 24 4
gpt4 key购买 nike

我正在开发一个应用程序,其中包括在目录中选择一个文件(.csv)并将数据导入到数据库(mysql)中,但出现以下错误:

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

下面是测试界面中包含功能的完整代码:

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

最佳答案

首先,您应该从 browse_file 函数返回路径。试试这个:

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

关于Python/MySQL - 将csv文件导入mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59739971/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com