gpt4 book ai didi

python - Python 中的 MySQL 连接器不允许 LOAD DATA INFILE 语法

转载 作者:行者123 更新时间:2023-12-02 07:04:09 44 4
gpt4 key购买 nike

我正在尝试将文本文件发送到 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()

最佳答案

我刚看到这篇旧帖子,但这些答案都没有解决我的问题。

我看到了 here有一个专用于 LOCAL DATA INFILE 的参数:allow_local_infile=True
所以可以这样做:

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

关于python - Python 中的 MySQL 连接器不允许 LOAD DATA INFILE 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15233244/

44 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com