【发布时间】: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