簡體   English   中英

使用psycopg2而沒有SQLAlchemy的Pandas數據幀到PostgreSQL表?

[英]Pandas dataframe to PostgreSQL table using psycopg2 without SQLAlchemy?

我想在不使用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))

參考代碼: 將數據幀復制到postgres表,其中包含具有defalut值的列

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM