chat1
import duckdb
import pandas as pd
def store_dataframe_to_duckdb(df, db_path, table_name):
# Connect to DuckDB
con = duckdb.connect(db_path)
# Directly create or replace the table from the DataFrame
con.register('df_view', df) # Register DataFrame as a temporary view
con.execute(f"CREATE TABLE IF NOT EXISTS {table_name} AS SELECT * FROM df_view")
con.unregister('df_view') # Optionally, unregister the view after use
# Commit changes and close the connection
con.commit()
con.close()
# Example usage
df = pd.DataFrame({
'id': [1, 2, 3],
'name': ['Alice', 'Bob', 'Charlie'],
'age': [25, 30, 35]
})
store_dataframe_to_duckdb(df, 'my_database.duckdb', 'people')