如何使用sql alchemy与postgresql建立数据库连接,并将dataframe或csv插入postgresql数据库?

2024-04-25 04:01:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我的主要任务是将数据帧转换或摄取到postgressql数据库

我想用sqlalchemy连接数据库,所以我想用下面的代码连接我的postgressql数据库。请帮我解决这个错误。 以下是我的pgadmin的详细信息: 服务器名称:test 用户名:postgre 密码 港口:5432 主机:本地主机 在测试服务器中,我有两个数据库,它们是postgre和stores,我希望将数据帧摄取到stores数据库中

import sqlalchemy               #package to access the sql databases via Python
import psycopg2

#connect to database
engine = sqlalchemy.create_engine("postgresql://postgres:password@localhost/stores")

#verify there are no existing tables
print(engine.table_names())

这就是我在运行上述代码后遇到的错误

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

40 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?


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

OperationalError                          Traceback (most recent call last)
/usr/local/lib/python3.6/dist-packages/psycopg2/__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
    128     if cursor_factory is not None:
    129         conn.cursor_factory = cursor_factory
--> 130 
    131     return conn

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/13/e3q8)

Tags: theto数据库localhostserversqlalchemyison