Sorry for what is probably a simple question. I've been working with pandas for a little & have had no trouble loading excel files into MSSQL, however, I haven't been able to figure it out for mysql. I wasn't able download the MySQLdb package, so I installed the mysql package & used mysql.connector as shown below:
Original Code
import pandas as pd
import mysql.connector as mysql
data = pd.read_excel(r"[my file path]")
df = pd.DataFrame(data, columns=['Name', 'country', 'age', 'gender'])
conn = mysql.connect('Driver={SQL Server};'
'Server=[my server name];'
'Database=[my database];'
'Trusted_Connection=yes;')
cursor = conn.cursor()
print(df)
for row in df.itertuples():
cursor.execute('''
INSERT INTO [database].dbo.[table] (Name, country, age, gender)
VALUES (?,?,?,?)
''',
row.Name,
row.country,
row.age,
row.gender
)
conn.commit()
Not sure what exactly I should be doing to make this all work.
Code that works
import mysql.connector
import pandas as pd
conn= mysql.connector.connect(user='[username]', password='[password]', host='[hostname]', database='[databasename]')
cursor = conn.cursor()
excel_data = pd.read_excel(r'[filepath]',sep=',', quotechar='\'')
for row in excel_data.iterrows():
testlist = row[1].values
cursor.execute("INSERT INTO [tablename](Name, Country, Age, Gender)"
" VALUES('%s','%s','%s','%s')" % tuple(testlist))
conn.commit()
cursor.close()
conn.close()
More concise code which also works
import pandas as pd
from sqlalchemy import create_engine, types
engine = create_engine('mysql://root:[password]@localhost/[database]') # enter your password and database names here
df = pd.read_excel(r"[file path]",sep=',',quotechar='\'',encoding='utf8') # Replace Excel_file_name with your excel sheet name
df.to_sql('[table name]',con=engine,index=False,if_exists='append') # Replace Table_name with your sql table name