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")
import pandas as pd
import sqlite3
# Name of the CSV file to convert
csv_file = 'Titanic-Dataset.csv'
# Name of the SQLite database file to create
db_file = 'titanic.db'
# Name of the table within the SQLite database
table_name = 'titanic_data'
# Read the CSV file into a pandas DataFrame
df = pd.read_csv(csv_file)
# Create an SQLite database connection
conn = sqlite3.connect(db_file)
# Write the DataFrame to an SQLite table
df.to_sql(table_name, conn, if_exists='replace', index=False)
# Close the connection
conn.close()
print(f"Successfully converted '{csv_file}' to SQLite database '{db_file}' with table '{table_name}'.")
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 & 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.