In the preceding program, a single record is inserted using the insert command. If we want to insert multiple records, we need to run a loop to insert the multiple records into the database. We can also use the to_sql() function to insert multiple records in a single line of code:
# Import the sqlalchemy engine
from sqlalchemy import create_engine
# Instantiate engine object
en = create_engine("mysql+pymysql://{user}:{pw}@localhost/{db}"
.format(user="root",
pw="root",
db="emp"))
# Insert the whole dataframe into the database
df.to_sql('emp', con=en, if_exists='append',chunksize=1000, index= False)
In the preceding code example, we will create an engine for a database connection with username, password, and database parameters. The to_sql() function writes multiple records from the DataFrame to a SQL database...