python将doc导入数据库_用python将路径文件导入mysql数据库表

这篇博客展示了如何使用Python的Flask框架创建一个文件上传接口,特别是处理CSV文件。用户可以上传CSV文件,然后应用使用MySQL数据库加载数据。代码中包含了文件类型检查、文件保存以及使用LOAD DATA LOCAL INFILE SQL语句将数据导入到数据库的步骤。
摘要由CSDN通过智能技术生成

请尝试以下代码。

我试过了,效果很好。在

请修复password和host,以及{}的host。在import os

from flask import Flask, request, redirect, url_for, send_from_directory

from werkzeug import secure_filename

import MySQLdb

import glob

UPLOAD_FOLDER ="/tmp/"

ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'csv'])

app = Flask(__name__)

app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):

# this has changed from the original example because the original did not work for me

return filename[-3:].lower() in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])

def upload_file():

if request.method == 'POST':

file = request.files['file']

if file and allowed_file(file.filename):

print '**found file', file.filename

filename = secure_filename(file.filename)

file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

conn = MySQLdb.connect (host="127.0.0.1", port=3306, user="root",passwd="kani",db="myDb", local_infile = 1)

x = conn.cursor()

print 'filename'

sql = """LOAD DATA LOCAL INFILE '{}'

INTO TABLE test

FIELDS TERMINATED BY ','

OPTIONALLY ENCLOSED BY '"'

LINES TERMINATED BY '\n'

IGNORE 1 LINES

"""

os.chdir(UPLOAD_FOLDER)

dirfiles=glob.glob("*.csv")

for file_name in dirfiles:

print file_name

if file_name==filename:

try:

cursor = conn.cursor()

file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)

print sql.format(file_path)

cursor.execute(sql.format(file_path))

conn.commit()

print "hello"

except Exception, e:

print e

# Rollback in case there is any error

conn.rollback()

# for browser, add 'redirect' function on top of 'url_for'

return url_for('uploaded_file',

filename=filename)

return '''

Upload new File

Upload new File

'''

@app.route('/uploads/')

def uploaded_file(filename):

return send_from_directory(app.config['UPLOAD_FOLDER'],

filename)

if __name__ == '__main__':

app.run(host='192.168.33.40', port=5000, threaded=True,debug=True)

您应该将local_infile = 1插入MySQLdb.connect,以便使用LOAD DATA语句。在

编辑

抱歉,如果只想插入csv文件的路径,则不需要local_infile=1。在

简单地说,请修复您的sql。。在

sql = "INSERT into test (file_path) values ('{}')"

这是你想要的吗?在

编辑

您可以获得如下文件路径。在

file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)

并且,通过使用format方法

sql.format(file_path)

您的sql如下所示。在

INSERT into test (file_path) values ('/tmp/hoge.csv')

你能试试上面的吗?在

附言

^{pr2}$

我希望一切顺利。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值