使用python将路径文件导入mysql db表

时间:2017-08-02 04:07:23

标签: python mysql csv

我真的需要你的帮助。我将保存我的csv文件的路径并插入mysql db表的路径。这是我的代码。此代码只插入csv的数据而不是路径文件。

import os
from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
import MySQLdb
import glob
UPLOAD_FOLDER ="/var/lib/mysql-files/"
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="192.168.1.5", port=3306, user="root",passwd="12345fitri",db="myDb")
        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
        (FILE);"""  

        #"
        os.chdir(UPLOAD_FOLDER)
        dirfiles=glob.glob("*.csv")
        for file_name in dirfiles:
          print file_name
          if file_name==filename:
        try:
            cursor = conn.cursor()
            cursor.execute(sql.format(file_name))
            conn.commit()
            print "hello"
        except Exception:
            # 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 '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''
#
@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000,  threaded=True,debug=True)

3 个答案:

答案 0 :(得分:0)

请尝试以下代码。 我试过了,但它确实有效。

请修复password的{​​{1}}和host以及MySQLdb.connect的{​​{1}}。

host

您应该将app.run插入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 ''' <!doctype html> <title>Upload new File</title> <h1>Upload new File</h1> <form action="" method=post enctype=multipart/form-data> <p><input type=file name=file> <input type=submit value=Upload> </form> ''' @app.route('/uploads/<filename>') 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声明。

修改

很抱歉,如果您只想插入csv文件的路径,则不需要MySQLdb.connect

简单地说,请修正您的LOAD DATA ..

local_infile=1

这是你想要的吗?

修改

您可以按如下方式获取文件路径。

sql

并使用sql = "INSERT into test (file_path) values ('{}')"方法

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

你的sql将如下所示。

format

你能尝试一下吗?

P.S

sql.format(file_path)

我希望它顺利。

答案 1 :(得分:0)

 import os
from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
import MySQLdb
import glob
UPLOAD_FOLDER ="/var/lib/mysql-files/"
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="192.168.1.1", port=3306, user="root",passwd="1234",db="myDb")
        x = conn.cursor()
            print 'filename'
        sql = "INSERT INTO mine (filepath) values('/var/lib/mysql-files/', 'filename')"

        os.chdir(UPLOAD_FOLDER)
        dirfiles=glob.glob("*.csv")
        for file_name in dirfiles:
          print file_name
          if file_name==filename:
        try:
            cursor = conn.cursor()
            cursor.execute(sql.format(file_name))
            conn.commit()
            print "hello"
        except Exception:
            # 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 '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000,  threaded=True,debug=True)

答案 2 :(得分:0)

    import os
from flask import Flask, request, redirect, url_for, send_from_directory
from werkzeug import secure_filename
import MySQLdb
import glob
UPLOAD_FOLDER ="/var/lib/mysql-files/"
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="192.168.1.5", port=3306, user="root",passwd="12345fitri",db="myDb")
        x = conn.cursor()
            print 'filename'
        sql = "INSERT INTO mine (what) values('/var/lib/mysql-files/')"

        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:
            # 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 '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form action="" method=post enctype=multipart/form-data>
      <p><input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000,  threaded=True,debug=True)