Pandas dataframe to PostgreSQL table using psycopg2 without



我想在不使用SQLAlchemy的情况下将Pandas数据帧写入PostgreSQL表。

表名应与 pandas 变量名相对应,如果已存在,则替换表。数据类型也需要匹配。

出于几个原因,我想避免使用SQLAlchemy的to_sql函数。

import pandas as pd
from getpass import getpass
import psycopg2
your_pass = getpass(prompt='Password: ', stream=None)
conn_cred = {
    'host': your_host,
    'port': your_port,
    'dbname': your_dbname,
    'user': your_user,
    'password': your_pass
}
conn = psycopg2.connect(**conn_cred)
conn.autocommit = True
my_data = {'col1': [1, 2], 'col2': [3, 4]}
def store_dataframe_to_postgre(df, schema, active_conn):
    # df = pandas dataframe to store as a table
    # schema = schema for the table
    # active_conn = open connection to a PostgreSQL db
    # ...
    # Bonus: require explicit commit here, even though conn.autocommit = True

store_dataframe_to_postgre(my_data, 'my_schema', conn)

这应该是 Postgre 数据库中的结果:

SELECT * FROM my_schema.my_data;
   col1  col2
     1     3
     2     4

你可以试试,但这段代码在你的:

 cursor = conn.cursor()  
 cur.copy_from(df, schema , null='', sep=',', columns=(my_data))

参考代码:将数据帧复制到具有 defalut 值的列的 Postgres 表

最新更新