from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://usrid:password@localhost/my_db")
import pandas as pd
my_dict={
'class':['Five','Six','Three'],
'No':[5,2,3]
}
df = pd.DataFrame(data=my_dict)
import pandas as pd
my_conn=create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
my_dict={
'class':['Five','Six','Three'],
'No':[5,2,3]
}
df = pd.DataFrame(data=my_dict)
df.to_sql(con=my_conn,name='student2',if_exists='append',index=False)
import pandas as pd
from sqlalchemy import create_engine
my_conn=create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
query="SELECT * FROM student WHERE class='Five'"
df=pd.read_sql(query,my_conn)
print(df) # Data taken from table and DataFrame output
df.to_sql(con=my_conn,name='student2',if_exists='append', index=False)
The last line in above code will insert the DataFrame to MySQL database in a new table student2.
if_exists='replace'
query="SELECT * FROM student2"
df=pd.read_sql(query,my_conn)
print(df)
df['mark']=df['mark']+5
df.to_sql(con=my_conn,name='student2',if_exists='replace', index=False)
To check the updated data we can run this code.
query="SELECT * FROM student2"
df=pd.read_sql(query,my_conn)
print(df)
Output ( sample)
id name class mark gender
0 7 My John Rob Five 83 male
1 8 Asruid Five 90 male
2 18 Honny Five 80 male
student3=pd.read_excel("D:\my_data\student.xlsx")
#student3=pd.read_csv("D:\my_data\student.csv")# CSV file reading
df=pd.DataFrame(data=student3)
print(df)
df.to_sql(con=my_conn,name='student3', if_exists='append',index=False)
If you are using a large file or more number of records then to show a sample records from top we can use head() or to show last records tail().
print(df.head())
print(df.tail())
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.