Python中的MySQL连接器不允许加载数据填充语法

2024-04-25 20:08:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将一个文本文件发送到MySQL数据库中。我试图用python3.2中的mysql连接器来实现这一点。问题在于加载数据填充语法。你可以在上面找到我的代码。我的第一个问题是有没有办法解决这个问题。注意,我已经尝试过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()        

Tags: nameimportexecutedbtablesconnectorlocalmysql
3条回答

我也有类似的问题。我不熟悉python和mysqldb。我加了一个连接提交而且成功了。 它似乎通过要求提交来保护数据库。在

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

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

我在这里回答了同样的问题:https://stackoverflow.com/a/25495823/2364773

简而言之,您需要使用client_flags参数在连接中添加客户机标志

相关问题 更多 >