繁体   English   中英

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

[英]Import path file to mysql db table with python

我确实需要您的帮助。 我将保存我的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)

请尝试以下代码。 我尝试了一下,它奏效了。

请修复passwordhostMySQLdb.connect ,和hostapp.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 = 1MySQLdb.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')

你可以尝试以上吗?

PS

    sql = "INSERT into test (file_path) values ('{}')"
    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()

我希望这会顺利。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM