I'm trying to import a csv file into mysql using python for practice. I believe I've downloaded the right libraries. Every time I run my code I get the error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)' at line 1
I can't figure out why this won't work and all answers seem to be using mysqldb, which doesn't support python 3.x.
My code:
import mysql.connector
import pandas as pd
cnx = mysql.connector.connect(user='root', password='comeonin', host='127.0.0.1', database='boxresults')
cursor = cnx.cursor()
csv_data = pd.read_csv('Betting/boxresults3.csv')
for row in csv_data:
cursor.execute("INSERT INTO table1(Week, Day, Date, Winner, Loser, PtsW, PtsL, YdsW, TOW, YdsL, TOL) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s, %s)", row)
cursor.close()
cnx.close()
New Code:
import mysql.connector
import pandas as pd
cnx = mysql.connector.connect(user='root', password='comeonin', host='127.0.0.1', database='boxresults')
cursor = cnx.cursor()
csv_data = pd.read_csv('Betting/boxresults3.csv')
for row in csv_data.iterrows():
list = row[1].values
cursor.execute("INSERT INTO table1(Week, Day, Date, Winner, Loser, PtsW, PtsL, YdsW, TOW, YdsL, TOL) VALUES('%d','%s','%s','%s','%s','%d','%d','%d','%d','%d', '%d')" % tuple(list))
cursor.close()
cnx.close()
You have wrong row
.
for row in csv_data
gives you column name in row
To get row you need iterrows()
for row in csv_data.iterrows():
But this row
has not only values
but other information. You values are in row[1]
but as Series
object so you need values
to get values as list
for row in csv_data.iterrows():
print( row[1].values )
Full working example:
import pandas as pd
df = pd.DataFrame([[1,2,3], [4,5,6]], columns=['a','b','c'])
print(df)
for row in df.iterrows():
print('type:', type(row[1]))
print('values:', row[1].values)
Results:
a b c
0 1 2 3
1 4 5 6
type: <class 'pandas.core.series.Series'>
values: [1 2 3]
type: <class 'pandas.core.series.Series'>
values: [4 5 6]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.