Python中的MySQL连接器不允许使用LOAD DATA INFILE语法

4 投票
6 回答
10256 浏览
提问于 2025-04-17 18:02

我正在尝试把一个文本文件导入到MySQL数据库中。我是用Python 3.2的mysql连接器来做这件事的。问题出在LOAD DATA INFILE这个语法上。你可以在上面找到我的代码。我的第一个问题是,有没有办法解决这个问题。请注意,我尝试过local-infile=1这个选项,但Python不允许使用这个选项。第二个问题是,还有没有其他方法可以把这些数据作为一个整体发送到MySQL数据库中?

from __future__ import print_function
import os
import mysql.connector
from mysql.connector import errorcode
config = {
    'user':'root',
    'password':'3778',
##  'host':'localhost',
#   'database':'microstructure',
#    'local-infile':'1',
    }


DB_NAME = 'EURUSD'
TABLES ={}
TABLES['microstructure']=(
    "CREATE TABLE `microstructure` ("
   # "  `p_id` int NOT NULL AUTO_INCREMENT,"
    "  `ticker` varchar(255),"
    "  `time` date,"
    "  `last_price` decimal(6,3)"
    ") ENGINE=InnoDB")

TABLES['cumulative']=(
    "CREATE TABLE `cumulative` ("
    "  `p_id` int NOT NULL AUTO_INCREMENT,"
    "  `ticker` varchar(255),"
    "  `time` date,"
    "  `last_price` decimal(6,3),"
    "  PRIMARY KEY(`p_id`)"
    ") ENGINE=InnoDB")

cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
path_txt = 'C:/Users/ibrahim/Desktop/testfile.txt'

def create_database(cursor):
    try:
        cursor.execute(
            "CREATE DATABASE IF NOT EXISTS {} DEFAULT CHARACTER SET 'utf8'".format(DB_NAME))
    except mysql.connector.Error as err:
            print("Failed creating database: {}".format(err))
            exit(1)
try:
    cnx.database = DB_NAME
except mysql.connector.Error as err:
    if err.errno == errorcode.ER_BAD_DB_ERROR:
        create_database(cursor)
        cnx.database=DB_NAME
    else:
        print(err)
        exit(1)

for name, ddl in TABLES.items():
    try:
        print("Creating table {}: ".format(name), end ='')
        cursor.execute(ddl)
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
            print("Already exists")
        else:
            print(err)

    else:
        print("OK")

cursor.execute("SET @@global.local_infile = 1")

cursor.execute("LOAD DATA LOCAL INFILE 'testfile.txt' into table microstructure")

os.system("start")

cursor.close()        

6 个回答

4

我也遇到过类似的问题。我刚开始学Python和MySQL数据库。我加了一句conn.commit,结果就好了。看起来这个操作是为了保护数据库,要求你必须提交更改。

4

在MySQLdb中,我使用这个来启用 LOAD DATA LOCAL INFILE 功能:

MySQLdb.connect(..., local_infile=True)
13

我刚看到这个旧帖子,但这些回答都没能解决我的问题。

我在这里看到,有一个专门用于本地数据导入的参数:allow_local_infile=True

所以可以这样做:

mysql.connector.connect(user='[username]', password='[pass]', host='[host]', allow_local_infile=True)

撰写回答