from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:password@localhost/my_database") #fill details
my_conn=my_conn.connect() # add this line if error
Above code we will use in our examples to manage our connection to MySQL. Note the connection variable my_conn
df.to_sql(con=my_conn,name='student2',if_exists='append')
to_sql() is used to Create & insert Data to MySQL database table
fail
: (default) Generate a value errorreplace
: Drop the table and then insert new valuesappend
: Add new data to the table.
index
:(optional) Boolean , if True ( default ) index will be added to the table, in case of False no index will transfer along with records.
df.to_sql(con=my_conn,name='student2',if_exists='append', index=False)
If the table already have index column and we set index=False then NULL data will be inserted in index column. If there is no index column and we set if_exists='append' and index=True then we will get error message.
OperationalError: (MySQLdb._exceptions.OperationalError) (1054, "Unknown column 'index' in 'field list'")
from sqlalchemy import create_engine,Float
Here we are specifying that the columns Sp_Mobile and Sp_Desktop should be SQLAlchemy Float type.
df.to_sql(con=my_conn,name=d,if_exists='replace',
index=False,dtype={"Sp_Mobile": Float,"Sp_Desktop":Float})
my_data['c_date']=pd.to_datetime(my_data['c_date'],format='%d.%m.%Y')
The format option given in above code as format='%d.%m.%Y' is your available input format of original DataFrame.
import pandas as pd
df = pd.read_excel('D:\emp.xlsx')
# reading data from root of D drive.
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:pw@localhost/db_name")
### Creating new table emp or appending existing table
df.to_sql(con=my_conn,name='emp',if_exists='append')
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:pw@localhost/db_name")
df = pd.read_csv("F:\\data\\student.csv") # Path of the csv file, create dataframe
df.to_sql(con=my_conn, name="student5", if_exists="append")
to_sql()
function in Pandas to save a DataFrame to a SQL database?to_sql()
function in Pandas?to_sql()
function?to_sql()
function when creating a table in the database?to_sql()
?to_sql()
function?to_sql()
?to_sql()
?to_sql()
?to_sql()
?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.