Skip to main content

chat1

import duckdb
import pandas as pd

def store_dataframe_to_duckdb(append_dataframe_to_duckdb(df, db_path, table_name):
    # Connect to DuckDB
    con = duckdb.connect(db_path)

  

    # Directly create or replaceRegister the table from the DataFrame
    con.register('df_view', df)  # Register DataFrame as a temporary view
    con.register('df_view', df)

    # Check if the table exists and if not, create it from the DataFrame
    con.execute(f"""
    CREATE TABLE IF NOT EXISTS {table_name} AS SELECT * FROM df_view WHERE 1=0;
    """)

    # Insert new data into the existing table
    con.execute(f"INSERT INTO {table_name} SELECT * FROM df_view")

    # Unregister the view and close the connection
    con.unregister('df_view')  # Optionally, unregister the view after use
    
    # Commit changes and close the connection
    con.commit()
    con.close()

# Example usageDataFrame
df = pd.DataFrame({
    'id': [1, 2, 3]4],
    'name': ['Alice', 'Bob', 'Charlie']None],
    'age': [25, 30, 35]40]
})

store_dataframe_to_duckdb(# Append the DataFrame to the existing DuckDB table
append_dataframe_to_duckdb(df, 'my_database.duckdb', 'people')