i have the following notebook, where im trying to insert the data of a dataframe into my phpmyadmin sql database to replicate run the following:
first i create the Database with the schema
CREATE SCHEMA IF NOT EXISTS `proyecto` DEFAULT CHARACTER SET utf8 ;
USE `proyecto`;
CREATE TABLE IF NOT EXISTS `pueblos`(
`Pueblo` VARCHAR(60) NOT NULL,
`Comunidad` VARCHAR(60) NOT NULL,
`Provincia` VARCHAR(60) NOT NULL,
`Latitud` float NOT NULL,
`Longitud` float NOT NULL,
`Altitud` float NOT NULL,
`Habitantes` int NOT NULL,
`Hombres` int NOT NULL,
`Mujeres` int NOT NULL,
PRIMARY KEY (`Pueblo`))
ENGINE = InnoDB;
and in python i import the libraries
import numpy as np
import pandas as pd
pip install mysqlclient
import MySQLdb
then i gather the data and transform it like so
df= pd.read_excel('https://www.businessintelligence.info/resources/assets/listado-longitud-latitud-municipios-espana.xls')
df=df.drop(index = 0)
new_header = df.iloc[0]
df= df[1:]
df.columns = new_header
So far we have the data and the DB Schema, and so far so good. now, i try to insert some data to make sure the connection works so i run
db=MySQLdb.connect("localhost","root","","proyecto")
insertrec=db.cursor()
a="se"
b="ha"
c="insertado"
sqlquery="INSERT INTO Pueblos (Pueblo, Comunidad,Provincia,Latitud,Longitud,Altitud,Habitantes,Hombres,Mujeres) VALUES('"+a+"', '"+b+"','"+c+"',7,8,9,10,11,12)"
insertrec.execute(sqlquery)
db.commit()
print("Success!!")
db.close()
and i can see that im able to insert data into my database, great! so the issue comes when i try to now replicate the same and insert the data of my dataframe like this
for index, row in df.iterrows():
Pueblo=row['Población']
Comunidad=row['Comunidad']
Provincia=row['Provincia']
Latitud=row['Latitud']
Longitud=row['Longitud']
Altitud=row['Altitud']
Habitantes=row['Habitantes']
Hombres=row['Hombres']
Mujeres=row['Mujeres']
sqlquery="INSERT INTO Pueblos (Pueblo, Comunidad,Provincia,Latitud,Longitud,Altitud,Habitantes,Hombres,Mujeres) VALUES(row['Población'], row['Comunidad'],row['Provincia'], row['Latitud'],row['Longitud'],row['Altitud'],row['Habitantes'],row['Hombres'],row['Mujeres'])"
insertrec.execute(sqlquery)
db.commit()
db.close()
this operation fails.
What am i doing wrong, i believe im simply doing the same as the simple insertion but i cant understand why it doesnt work
EDIT currently attempting to implement @buran suggestion, to use df.to_sql, but it still fails the code attempted is
df.to_sql("pueblos",db,if_exists='append',index=False)
EDIT 2 the thread questions about pandas.to_sql points that df.to_sql is no longer supported, so we are currently creating an engine and attempting it through their solution. the first change was to add the column index with type int into the db schema, since df.to_sql also takes the index i also made a an user ana with password ana with same priviledges as root for the engine syntax from there attempting to implement their solution like so
from sqlalchemy import create_engine
engine = create_engine("mysql://ana:ana@localhost/proyecto")
con = engine.connect()
df.to_sql(name='pueblos',con=con,if_exists='append')
con.close()
currently this yields the error: OperationalError: (MySQLdb._exceptions.OperationalError) (1054,NULL)