Reputation: 277
Suppose i i have a dataframe df and it has the same columns as a sql table. What is the simplest (and most efficient way) to insert the dataframe into a table.
import pandas as pd
from sqlalchemy import create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
df = pd.DataFrame({'name' : ['User 1', 'User 2', 'User 3']})
engine = create_engine('sqlite:///database.db')
conn = engine.connect()
Base = automap_base()
Base.prepare(engine, reflect=True)
session = Session(bind=engine)
# No assume that the database has a table Users with one column "name"
# is there a function, which adds all entries of the dataframe to the sql table?
# This should also works with dates/floats type of columns and multiple columns
Upvotes: 1
Views: 172
Reputation: 18406
Simplest way? Just use
df.to_sql('tableName', databaseConnectionObject, if_exists='append')
I think it is efficient as well, but can't say whether it is the most efficient or not, you need to test out the things
Upvotes: 3