I have the following script in python3.4 to insert data into a MySQL table:
import pymysql
connection = pymysql.connect(host='localhost',user='root',password='',db='bd',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor)
cursor = connection.cursor()
try:
query = "LOAD DATA LOCAL INFILE 'C:/data.csv' INTO TABLE bd.down_data
FIELDS TERMINATED BY '\t' ESCAPED BY '"'
LINES TERMINATED BY '\n' IGNORE 1 LINES
(campo1, campo2, campo3);"
cursor.execute(query)
print('LOAD OK')
except:
print('query failed')
result = cursor.fetchone()
connection.close()
and I get the following error:
query failed
Traceback <most recent call last>:
File "test.py", line 14, in<module>
result=cursor.fetchone()
File "C:\Python34\lib\site-packages\pymysql\cursors.py", line 282, in fetchone self._check_executed()
File "C:\Python34\lib\site-packages\pymysql\cursors.py" line 78, in _check_executed
raise err.ProgrammingError<"execute() first">
pymysql.err.ProgrammingError: execute() first
If I run the SQL directly in MySQL, does it work without problems, some idea of what I'm doing wrong?
********** UPDATE ***********
Add the local_infile=True
statement to the connection
import pymysql
connection = pymysql.connect(host='localhost',user='root',password='',db='bd',charset='utf8mb4',cursorclass=pymysql.cursors.DictCursor,local_infile=True)
cursor = connection.cursor()
try:
query = "LOAD DATA LOCAL INFILE 'C:/data.csv' INTO TABLE bd.down_data
FIELDS TERMINATED BY '|' ESCAPED BY '\"'
LINES TERMINATED BY '\n' (campo1, campo2, campo3);"
cursor.execute(query)
print('LOAD OK')
except TypeError as e:
print('query failed: '+e)
result = cursor.fetchone()
connection.close()
Now I see that you try to do the load
but it gives me the following warning:
C:\Python34\lib\site-packages\pymysql\cursors.py:329: Warning: <1262, ´Row 1 was truncated; it contained more data than there were input columns´>
self._do_get_result()
This warning also gives me workbench when executing the load data infile direct but I insert the data, so I guess the warning is because in my table MySQL
I have 3 columns and in the .csv
I have more than 3 columns, then I imagine that python
does not support it