尝试通过SQL-Alchemy建立与PgAdmin的连接时出现OperationalError

时间:2020-10-28 20:39:51

标签: python sqlalchemy anaconda psycopg2 pgadmin

作为我的数据科学课程的一部分,我们必须将python程序连接到我们创建的数据库中。我们得到了PG-Admin,SQL-Alchemy和psycopg2。但是,每当尝试建立与数据库的连接时,都会出现错误,我不知道如何解决。 我的代码如下:

import psycopg2 #provides drivers for PostgreSQL
import numpy as np
import json #required to access json file
import pandas as pd
from sqlalchemy import create_engine

with open('configTemplate.json') as f:
    conf = json.load(f)
print(type(conf))
print("Name of database is: ",conf['database'])
print("Name of user is: ",conf['user'])
conn_str ='postgresql://%s:%s@localhost:5432/%s'%(conf["user"], conf["passw"],conf["database"])
engine = create_engine(conn_str)
with engine.connect() as conn, conn.begin():
    data = pd.read_sql_table('test', conn)

这将创建以下输出:

<class 'dict'>
Name of database is:  datamining
Name of user is:  db_user

---------------------------------------------------------------------------
OperationalError                          Traceback (most recent call last)
~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\base.py in _wrap_pool_connect(self, fn, connection)
   2337         try:
-> 2338             return fn()
   2339         except dialect.dbapi.Error as e:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in unique_connection(self)
    303         """
--> 304         return _ConnectionFairy._checkout(self)
    305 

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in _checkout(cls, pool, threadconns, fairy)
    777         if not fairy:
--> 778             fairy = _ConnectionRecord.checkout(pool)
    779 

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in checkout(cls, pool)
    494     def checkout(cls, pool):
--> 495         rec = pool._do_get()
    496         try:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\impl.py in _do_get(self)
    139                 with util.safe_reraise():
--> 140                     self._dec_overflow()
    141         else:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\langhelpers.py in __exit__(self, type_, value, traceback)
     68                 compat.raise_(
---> 69                     exc_value, with_traceback=exc_tb,
     70                 )

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\compat.py in raise_(***failed resolving arguments***)
    181         try:
--> 182             raise exception
    183         finally:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\impl.py in _do_get(self)
    136             try:
--> 137                 return self._create_connection()
    138             except:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in _create_connection(self)
    308 
--> 309         return _ConnectionRecord(self)
    310 

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in __init__(self, pool, connect)
    439         if connect:
--> 440             self.__connect(first_connect_check=True)
    441         self.finalize_callback = deque()

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in __connect(self, first_connect_check)
    660             with util.safe_reraise():
--> 661                 pool.logger.debug("Error on connect(): %s", e)
    662         else:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\langhelpers.py in __exit__(self, type_, value, traceback)
     68                 compat.raise_(
---> 69                     exc_value, with_traceback=exc_tb,
     70                 )

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\compat.py in raise_(***failed resolving arguments***)
    181         try:
--> 182             raise exception
    183         finally:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in __connect(self, first_connect_check)
    655             self.starttime = time.time()
--> 656             connection = pool._invoke_creator(self)
    657             pool.logger.debug("Created new connection %r", connection)

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\strategies.py in connect(connection_record)
    113                             return connection
--> 114                 return dialect.connect(*cargs, **cparams)
    115 

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\default.py in connect(self, *cargs, **cparams)
    492         # inherits the docstring from interfaces.Dialect.connect
--> 493         return self.dbapi.connect(*cargs, **cparams)
    494 

~\AppData\Roaming\Python\Python37\site-packages\psycopg2\__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
    126     dsn = _ext.make_dsn(dsn, **kwargs)
--> 127     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    128     if cursor_factory is not None:

OperationalError: 

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

OperationalError                          Traceback (most recent call last)
<ipython-input-4-388c442643cd> in <module>
      1 conn_str ='postgresql://%s:%s@localhost:5432/%s'%(conf["user"], conf["passw"],conf["database"])
      2 engine = create_engine(conn_str)
----> 3 with engine.connect() as conn, conn.begin():
      4     data = pd.read_sql_table('test', conn)

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\base.py in connect(self, **kwargs)
   2263         """
   2264 
-> 2265         return self._connection_cls(self, **kwargs)
   2266 
   2267     @util.deprecated(

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\base.py in __init__(self, engine, connection, close_with_result, _branch_from, _execution_options, _dispatch, _has_events)
    102                 connection
    103                 if connection is not None
--> 104                 else engine.raw_connection()
    105             )
    106             self.__transaction = None

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\base.py in raw_connection(self, _connection)
   2370         """
   2371         return self._wrap_pool_connect(
-> 2372             self.pool.unique_connection, _connection
   2373         )
   2374 

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\base.py in _wrap_pool_connect(self, fn, connection)
   2340             if connection is None:
   2341                 Connection._handle_dbapi_exception_noconnection(
-> 2342                     e, dialect, self
   2343                 )
   2344             else:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\base.py in _handle_dbapi_exception_noconnection(cls, e, dialect, engine)
   1582         elif should_wrap:
   1583             util.raise_(
-> 1584                 sqlalchemy_exception, with_traceback=exc_info[2], from_=e
   1585             )
   1586         else:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\compat.py in raise_(***failed resolving arguments***)
    180 
    181         try:
--> 182             raise exception
    183         finally:
    184             # credit to

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\base.py in _wrap_pool_connect(self, fn, connection)
   2336         dialect = self.dialect
   2337         try:
-> 2338             return fn()
   2339         except dialect.dbapi.Error as e:
   2340             if connection is None:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in unique_connection(self)
    302 
    303         """
--> 304         return _ConnectionFairy._checkout(self)
    305 
    306     def _create_connection(self):

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in _checkout(cls, pool, threadconns, fairy)
    776     def _checkout(cls, pool, threadconns=None, fairy=None):
    777         if not fairy:
--> 778             fairy = _ConnectionRecord.checkout(pool)
    779 
    780             fairy._pool = pool

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in checkout(cls, pool)
    493     @classmethod
    494     def checkout(cls, pool):
--> 495         rec = pool._do_get()
    496         try:
    497             dbapi_connection = rec.get_connection()

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\impl.py in _do_get(self)
    138             except:
    139                 with util.safe_reraise():
--> 140                     self._dec_overflow()
    141         else:
    142             return self._do_get()

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\langhelpers.py in __exit__(self, type_, value, traceback)
     67             if not self.warn_only:
     68                 compat.raise_(
---> 69                     exc_value, with_traceback=exc_tb,
     70                 )
     71         else:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\compat.py in raise_(***failed resolving arguments***)
    180 
    181         try:
--> 182             raise exception
    183         finally:
    184             # credit to

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\impl.py in _do_get(self)
    135         if self._inc_overflow():
    136             try:
--> 137                 return self._create_connection()
    138             except:
    139                 with util.safe_reraise():

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in _create_connection(self)
    307         """Called by subclasses to create a new ConnectionRecord."""
    308 
--> 309         return _ConnectionRecord(self)
    310 
    311     def _invalidate(self, connection, exception=None, _checkin=True):

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in __init__(self, pool, connect)
    438         self.__pool = pool
    439         if connect:
--> 440             self.__connect(first_connect_check=True)
    441         self.finalize_callback = deque()
    442 

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in __connect(self, first_connect_check)
    659         except Exception as e:
    660             with util.safe_reraise():
--> 661                 pool.logger.debug("Error on connect(): %s", e)
    662         else:
    663             if first_connect_check:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\langhelpers.py in __exit__(self, type_, value, traceback)
     67             if not self.warn_only:
     68                 compat.raise_(
---> 69                     exc_value, with_traceback=exc_tb,
     70                 )
     71         else:

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\util\compat.py in raise_(***failed resolving arguments***)
    180 
    181         try:
--> 182             raise exception
    183         finally:
    184             # credit to

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\pool\base.py in __connect(self, first_connect_check)
    654         try:
    655             self.starttime = time.time()
--> 656             connection = pool._invoke_creator(self)
    657             pool.logger.debug("Created new connection %r", connection)
    658             self.connection = connection

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\strategies.py in connect(connection_record)
    112                         if connection is not None:
    113                             return connection
--> 114                 return dialect.connect(*cargs, **cparams)
    115 
    116             creator = pop_kwarg("creator", connect)

~\.conda\envs\DataScience\lib\site-packages\sqlalchemy\engine\default.py in connect(self, *cargs, **cparams)
    491     def connect(self, *cargs, **cparams):
    492         # inherits the docstring from interfaces.Dialect.connect
--> 493         return self.dbapi.connect(*cargs, **cparams)
    494 
    495     def create_connect_args(self, url):

~\AppData\Roaming\Python\Python37\site-packages\psycopg2\__init__.py in connect(dsn, connection_factory, cursor_factory, **kwargs)
    125 
    126     dsn = _ext.make_dsn(dsn, **kwargs)
--> 127     conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
    128     if cursor_factory is not None:
    129         conn.cursor_factory = cursor_factory

OperationalError: (psycopg2.OperationalError) 
(Background on this error at: http://sqlalche.me/e/13/e3q8)

问题似乎与psycopg2-module有关,但是我似乎找不到解决方法。我尝试将其安装在单独的环境中,我使用了pip安装以及conda安装,还尝试安装二进制文件。似乎什么也没用,我的教授也帮不了我。

我正在使用Anaconda和Jupyter Notebooks,并且正在使用Windows。任何帮助将不胜感激,因为我的课程确实需要它。非常感谢!

0 个答案:

没有答案
相关问题