Python与MySQL的问题
我正在尝试将一个很大的文本文件导入到MySQL数据库中。我的SQL语句如下:
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代码时,数据库里却没有导入任何数据呢?
1 个回答
2
Python的数据库API是隐式事务的。这意味着在执行数据库操作时,系统会自动处理事务。你可以试着在执行完操作后加上dbConnection.commit()
,这样可以确保你的更改被保存到数据库里。