
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:password@localhost/database_name")
We will use read_sql() to create the DataFrame by using the query.
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_tutorial")
query="SELECT * FROM student WHERE class='four'"
df = pd.read_sql(query,my_conn,index_col='id')
print(df)
Using the Pandas DataFrame df, we will use set_dataframe() to add the dataframe to google sheets.
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://id:pw@localhost/my_tutorial")
query="SELECT * FROM student WHERE class='four'"
df = pd.read_sql(query,my_conn,index_col='id')
print(df)
import pygsheets
path='G:\\My drive\\testing\\google-sheet\\creds1.json'
gc=pygsheets.authorize(service_account_file=path)
sh=gc.open('my_gsheets1')
wk1=sh[0]
wk1.clear() # remove previous data if any
wk1.set_dataframe(df,(1,1),copy_index=True, extend=True)

import pygsheets
path='G:\\My drive\\testing\\google-sheet\\creds1.json'
gc=pygsheets.authorize(service_account_file=path)
sh=gc.open('my_gsheets1')
wk1=sh[0]
df = wk1.get_as_df(index_column=1)
print(df)
# inserting dataframe to MySQL table: Part 2
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://root:test@localhost/my_tutorial")
df.to_sql(con=my_conn,name='student2',if_exists='append', index=False)
Pygsheets and google API authorization set_dataframe() Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.