chat1
import duckdb
import pandas as pd
def append_dataframe_to_duckdb(df, db_path, table_name):
# Connect to DuckDB
con = duckdb.connect(db_path)
# Register the 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')
con.commit()
con.close()
# Example DataFrame
df = pd.DataFrame({
'id': [4],
'name': [None],
'age': [40]
})
# Append the DataFrame to the existing DuckDB table
append_dataframe_to_duckdb(df, 'my_database.duckdb', 'people')