首页 > 解决方案 > 操作错误,无法连接到 postgresql 中的服务器连接被拒绝

问题描述

我正在尝试将数据从熊猫写入数据库。我正在运行在我的本地主机上运行的 postgresql 服务器。尝试使用 sqlalchemy 和 psycopg2 建立连接

我使用 pip 安装了 sqlalchemy,使用 pip psycopg2-binary 安装了 psycopg2。操作系统:windows 和 ubuntu

enter code here
import pandas as pd
import sqlalchemy
import psycopg2
people={
 'first':['lokesh','ramu','dhana'],
    'last':['reddy','reddy','reddy'],
    'mail':['lokesh@mail.com','ramu@mail.com','dhana@mail.com']
}
df=pd.Dataframe(people)
engine=sqlalchemy.create_engine('postgresql://postgres:admin@localhost:5432/postgres')
df.to_sql('sample_table',engine)

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
/usr/local/lib/python3.7/dist-packages/sqlalchemy/engine/base.py in _wrap_pool_connect(self, fn, connection)
   3210         try:
-> 3211             return fn()
   3212         except dialect.dbapi.Error as e:

47 frames
OperationalError: could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?
    enter code here

The above exception was the direct cause of the following exception:

OperationalError                          Traceback (most recent call last)
<string> in run_callable(self, callable_, *args, **kwargs)

/usr/local/lib/python3.7/dist-packages/psycopg2/__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
    128 
    129     dsn = _ext.make_dsn(dsn, **kwargs)
--> 130     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    131     if cursor_factory is not None:
    132         conn.cursor_factory = cursor_factory

OperationalError: (psycopg2.OperationalError) could not connect to server: Connection refused
    Is the server running on host "localhost" (127.0.0.1) and accepting
    TCP/IP connections on port 5432?
could not connect to server: Cannot assign requested address
    Is the server running on host "localhost" (::1) and accepting
    TCP/IP connections on port 5432?

(Background on this error at: http://sqlalche.me/e/14/e3q8)

标签: pythonpandaspostgresqlsqlalchemypsycopg2

解决方案


推荐阅读