我正在使用ubuntu 16.04,mysql 5.6.34。 python 3.5.2。
我似乎无法让我的脚本执行LOAD DATA INFILE语句,但它在使用python3交互模式的同一台机器上运行良好。
这是我的代码:
#!/usr/bin/python3
import mysql.connector
db = mysql.connector.connect(passwd=dbpwd,db=dbname,host=dbhostname,port=port_no,user=dbusername)
cursor = db.cursor()
insert_file = '/home/ubuntu/insert.csv'
db.get_warnings=True
q_event = ("LOAD DATA LOCAL INFILE '%s' INTO TABLE my_table FIELDS TERMINATED BY "
"',' OPTIONALLY ENCLOSED BY '\\\"' (col1,col2,col3)"
)
print(q_event.__repr__())
cursor.execute(q_event % insert_file)
print(cursor.rowcount)
print(cursor.statement.__repr__())
print(cursor.fetchwarnings())
db.commit()
我的输出如下:
'LOAD DATA LOCAL INFILE \'%s\' INTO TABLE my_table FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'\\"\' (col1,col2,col3)'
0
'LOAD DATA LOCAL INFILE '/home/ubuntu/insert.csv\' INTO TABLE my_table FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'\\"\' (col1,col2,col3)'
None
行数始终为0.无论我如何更改Load
语句的格式,我似乎都无法更改脚本结果;它只是失败,没有错误。
与此同时,在交互模式下运行时,我的工作正常:
>>> import mysql.connector; db = mysql.connector.connect(passwd="...",db="...",host="...",port=...,user="..."); cursor = db.cursor();db.get_warnings=True;
>>> cursor.execute("LOAD DATA LOCAL INFILE '%s' INTO TABLE my_table FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\\\"' (col1,col2,col3)" % "/home/ubuntu/insert.csv")
>>> cursor.rowcount
31
>>> cursor.statement
'LOAD DATA LOCAL INFILE \'/home/ubuntu/insert.csv\' INTO TABLE my_table FIELDS TERMINATED BY \',\' OPTIONALLY ENCLOSED BY \'\\"\' (col1,col2,col3)'
>>> cursor.fetchwarnings()
>>>
这是否应该在交互模式下工作,而不是在脚本中?