Flask 上传 CSV 文件并将行插入 MySQL 数据库

时间:2021-07-27 08:19:15

标签: python mysql csv flask

我试图将 csv 文件数据上传到 mysql 数据库。我在 parsecsv 中有一些错误。请帮忙。我是一个完整的初学者。我将非常感谢您的帮助。

我试图使用这个网站的代码 链接: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>

picture of the database

picture of file directories

error

0 个答案:

没有答案
相关问题