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)
# Store the DataFrame in DuckDB, automatically inferring the schema
con.execute(f"CREATE TABLE IF NOT EXISTS {table_name} AS SELECT * FROM ?", (df,))
# You can also use this method to replace or append data
# con.execute(f"INSERT INTO {table_name} SELECT * FROM ?", (df,))
# 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')