我试图将csv文件数据上传到mysql数据库。我在分析CSV时有一些错误。请帮忙。我完全是个初学者。我将非常感谢你的帮助。
我试图使用此网站链接中的代码:https://medevel.com/flask-tutorial-upload-csv-file-and-insert-rows-into-the-database/
我不知道我是否已经做了这个网站上说的一切。我不知道。
main.py
from flask import Flask, render_template, request, redirect, url_for
import os
from os.path import join, dirname, realpath
import pandas as pd
import mysql.connector
app = Flask(__name__)
# enable debugging mode
app.config["DEBUG"] = True
# Upload folder
UPLOAD_FOLDER = 'static/files'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
# Database
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="project"
)
mycursor = mydb.cursor()
mycursor.execute("SHOW DATABASES")
# View All Database
for x in mycursor:
print(x)
# Root URL
@app.route('/')
def index():
# Set The upload HTML templates '\templates\index.html'
return render_template('index.html')
# Get the uploaded files
@app.route("/", methods=['POST'])
def uploadFiles():
# get the uploaded file
uploaded_file = request.files['file']
if uploaded_file.filename != '':
file_path = os.path.join(app.config['UPLOAD_FOLDER'], uploaded_file.filename)
# set the file path
uploaded_file.save(file_path)
parseCSV(file_path)
# save the file
return redirect(url_for('index'))
def parseCSV(filePath):
# CVS Column Names
col_names = ['name','date']
# Use Pandas to parse the CSV file
csvData = pd.read_csv(filePath,names=col_names, header=None)
# Loop through the Rows
for i,row in csvData.iterrows():
sql = "INSERT INTO attendance (name,date) VALUES (%s, %s)"
value = (row['name'],row['date'])
mycursor.execute(sql, value, if_exists='append')
mydb.commit()
print(i,row['name'],row['date'])
if (__name__ == "__main__"):
app.run(port = 5000)
html代码(index.html)
<!doctype html>
<html>
<head>
<title>FLASK CSV File Upload</title>
</head>
<body>
<h1>Upload your CSV file</h1>
<form method="POST" action="" enctype="multipart/form-data">
<p><input type="file" name="file"></p>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
数据库图片
文件目录图片
错误
暂无答案!
目前还没有任何答案,快来回答吧!