How to Create a Table in a DataBase Using DataFrames?

LibPQ itself doesn’t provider a wrapper for writing tables, here’s an example one that I’ve written (with limited testing, so please use at your own caution!)

function load_table!(conn, df, tablename, columns=names(df))
    table_column_names = join(string.(columns), ", ")
    placeholders = join(("\$$num" for num in 1:length(columns)), ", ")
    data = select(df, columns)
    try
        LibPQ.execute(conn, "BEGIN;")
        LibPQ.load!(
            data,
            conn,
            "INSERT INTO $tablename ($(table_column_names)) VALUES ($placeholders)"
        )
        LibPQ.execute(conn, "COMMIT;")
    catch
        LibPQ.execute(conn, "ROLLBACK;")
    end
end
1 Like