使用 psycopg2 在没有 SQLAlchemy 的情况下将 Pandas 数据帧转换为 PostgreSQL 表?

Ale*_*x F 8 python postgresql psycopg2 dataframe pandas

我想在不使用 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)
Run Code Online (Sandbox Code Playgroud)

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

SELECT * FROM my_schema.my_data;
Run Code Online (Sandbox Code Playgroud)
   col1  col2
     1     3
     2     4
Run Code Online (Sandbox Code Playgroud)

You*_*eod 3

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

 cursor = conn.cursor()  
 cur.copy_from(df, schema , null='', sep=',', columns=(my_data))
Run Code Online (Sandbox Code Playgroud)

参考代码: 将数据帧复制到具有默认值列的 postgres 表