2013-03-05 59 views
1

我試圖將文本文件發送到MySQL數據庫。我想在python 3.2中使用mysql連接器來做到這一點。問題是關於LOAD DATA INFILE語法。你可以在上面找到我的代碼。無論如何,我的第一個問題是解決這個問題。請注意,我嘗試了local-infile = 1選項,Python不允許使用此選項。其次,有沒有其他方法可以將這些數據作爲塊發送到mysql數據庫中?Python中的MySQL連接器不允許LOAD DATA INFILE語法

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

回答

1

當MySQLdb的我用這個來啓用LOAD DATA LOCAL INFILE功能:

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

另外,在連接添加一個客戶端的標誌。不要忘記在db上做一個commit()。 – 2015-07-19 13:07:49

0

什麼版本mysql.connector您使用的是?我在1.0.11上,並且我得到了這個功能。我所做的是創建的data.txt三行(1,2,3),進入這個目錄,啓動蟒蛇3.3.1,然後跑:

import mysql.connector 
conn = mysql.connector.connect(database='test', user='test', password='xx') 
curs = conn.cursor() 
curs.execute('''CREATE TABLE foo (id text)''') 
curs.execute('''LOAD DATA INFILE '/<full path to>/data.txt' INTO TABLE foo''') 
curs.execute('''SELECT * FROM FOO''') 
print(curs.fetchall()) 
curs.execute('''DROP TABLE foo''') 

我的輸出:

[( '1'),( '2'),( '3')]

請注意,您需要將文件權限授予 '測試' 的用戶,例如,

GRANT FILE ON *.* TO 'test'@'localhost'; 
3

I也有類似的問題。我是python和mysqldb的新手。我添加了一個conn.commit,它工作。 它似乎通過要求提交來保護數據庫。