我想在不使用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 db中的结果:
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))

引用代码:
copy dataframe to postgres table with column that has defalut value

关于python - 使用psycopg2在不使用SQLAlchemy的情况下将Pandas数据框转换为PostgreSQL表?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54519912/

10-12 17:13
查看更多