2011-05-24 53 views
1

我想將大文本文件導入到MySQL數據庫中。 SQL語句如下:Python和MySQL問題

LOAD DATA INFILE '/tmp/epf/full/album_popularity_per_genre' 
INTO TABLE album_popularity_per_genre 
CHARACTER SET UTF8 FIELDS TERMINATED BY X'01' LINES TERMINATED BY '\n' 
IGNORE 45 LINES (export_date, storefront_id, genre_id, album_id, album_rank) 

上述工作,當我在phpMyAdmin運行它,但是當我用Python語言編寫一個簡單的函數,使用上面的SQL語句,我得到一個錯誤。

這裏是Python代碼,

def test(): 
    dbConnection = MySQLdb.connect(
    charset='utf8', 
    host='localhost', 
    user='root', 
    passwd='root', 
    db='epf') 

    cursor = dbConnection.cursor() 

    exStr = """LOAD DATA INFILE '/tmp/epf/full/album_popularity_per_genre' 
       INTO TABLE album_popularity_per_genre CHARACTER SET UTF8 
       FIELDS TERMINATED BY X'01' LINES TERMINATED BY '\n' 
       IGNORE 45 LINES 
       (export_date, storefront_id, genre_id, album_id, album_rank)""" 

    try: 
     cursor.execute(exStr) 
    except MySQLdb.Warning, e: 
     print "Warning %s" % (str(e)) 
    except MySQLdb.IntegrityError, e:  
     print "Error %d: %s" % (e.args[0], e.args[1]) 

    #Clean up 
    cursor.close() 
    dbConnection.close() 

我得到的是如下的錯誤,

Warning Data truncated for column 'album_rank' at row 1 

我現在的問題是,爲什麼原始SQL語句的工作,但是當我嘗試運行Python代碼,沒有數據被導入到數據庫中?

回答

2

Python DBAPI隱含事務性。執行後嘗試添加dbConnection.commit()

+0

我想你的意思是'dbConnection.commit()'。我試過了,但我仍然遇到同樣的問題。謝謝。 – David 2011-05-24 16:38:04

+0

我只是重新檢查數據庫,你的建議確實奏效。謝謝。我也犯了一個錯誤警告錯誤。我會忽略那個警告。 – David 2011-05-24 16:48:30