使用psycopg2而不使用SQLAlchemy,将Pandas数据框架存储到PostgreSQL表中?

9
我希望能够将Pandas数据框架写入PostgreSQL表中,不使用SQLAlchemy。表名应该对应于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

这是你需要的 -> http://initd.org/psycopg/docs/extras.html#psycopg2.extras.execute_values - gold_cy
我不确定如何处理数据类型(数据不会有任何自定义类型)。 - Alex F
1个回答

3
你可以尝试在你的代码中加入以下内容:“最初的回答”。请注意保留HTML标签。
 cursor = conn.cursor()  
 cur.copy_from(df, schema , null='', sep=',', columns=(my_data))

参考代码: 将数据框复制到具有默认值列的Postgres表中

原始答案翻译成“最初的回答”。

请注意,本次翻译涉及IT技术相关内容。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接