【问题标题】:Saving a Pandas Dataframe to a PostgreSQL Server in AWS Redshift将 Pandas 数据框保存到 AWS Redshift 中的 PostgreSQL 服务器
【发布时间】:2019-02-24 09:56:15
【问题描述】:

我正在尝试将 pandas 数据框保存到 postgresql redshift 服务器。我所做的是连接到服务器,将表转换为数据框,进行一些分析,然后我想将其作为 postgresql 表保存回 AWS Redshift 服务器。

这是我的代码:

import pandas.io.sql as psql
import pandas as pd
import psycopg2
from sqlalchemy import create_engine
import datetime as dt
import warnings
import numpy as np
warnings.filterwarnings("ignore")
#importing dependecies

print("Importing Dependencies")

#setting up the connection
conn_string = "dbname='database_name' user='username' password='password'"
conn = psycopg2.connect(conn_string)
print("Connecting to Database")

#read each table as a data frame
df_1 = psql.read_sql("SELECT name, salary, date FROM A", conn)
df_2 = psql.read_sql("SELECT name, gender FROM B", conn)
df_3 = psql.read_sql("SELECT name, health, recovery_time FROM C", conn)

我在这里做了一些数据分析,然后尝试通过

保存我的结果
#Step 16: Saving result to postgresql table
print('Saving Partial Result as PostgreSQL Table')
engine = create_engine('postgresql://username:password@xx.xxx.xx.xxx/database_name')
con = engine.connect()
df.to_sql('health_informatics', con, if_exist='replace')
print('Successfully Saved to PostgreSQL')

但是我收到一条错误消息:

sqlalchemy.exc.OperationalError: (psycopg2.OperationalError) FATAL: no pg_hba.conf entry for host "xx.xxx.xx.xxx", user "username",database "database_name", SSL off

我已经读到这是一个配置问题:

https://serverfault.com/questions/704810/postgresql-error-with-pg-hba-conf

https://github.com/PostgresApp/PostgresApp/issues/234

http://docs.sqlalchemy.org/en/latest/errors.html#error-e3q8

很遗憾,我无法访问私人服务器根目录。我想知道是否有解决此问题的方法,我无法将数据保存为 .csv 文件,因为这些数据有数百万行,并且是与健康记录相关的敏感数据。

【问题讨论】:

  • 不要在to_sql 调用中使用原始连接。直接使用引擎:df.to_sql('health_informatics', engine, if_exist='replace')

标签: python postgresql pandas sqlalchemy psycopg2


【解决方案1】:

pg_hba.conf

(psycopg2.OperationalError) FATAL:

您可以从异常错误日志中看到您正在尝试 之前无需配置即可访问您的数据库。

首先,您需要预先创建配置文件。 pg_hba.conf 文件的一般格式是一组记录。

initdb

默认方式。命令 initdb 初始化你的 pg_hba.conf。

可以将身份验证配置文件放在其他地方。 您可以在同一文件中编辑此选项。

【讨论】:

  • 感谢您提供的信息,很想询问一些有关如何执行此操作的网站。我无权访问服务器的根目录,我需要就建议的解决方案编写文档,非常感谢您访问网站。谢谢!
猜你喜欢
  • 1970-01-01
  • 2014-05-24
  • 2017-08-11
  • 2017-12-30
  • 2019-03-30
  • 2012-02-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多