使用Python和Postgresql测试数据库连接

时间:2019-06-13 15:54:55

标签: python-3.x postgresql dbconnection

我正在尝试用postgresql和python连接我的数据库。我还在Windows的同一目录中安装了psycopg2并运行了脚本。但仍然是相同的错误。

psycopg2 installed successfully
C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\Scripts>pip install psycopg2
Collecting psycopg2
  Using cached https://files.pythonhosted.org/packages/00/f3/afd8570a32712953c83
e6ba2d3ce3c7cfaa6eeeebf8879da14731445b793/psycopg2-2.8.2-cp37-cp37m-win32.whl
Installing collected packages: psycopg2
Successfully installed psycopg2-2.8.2

Execution error
C:\Users\Admin\PycharmProjects\Modern_Times\venv\Scripts\python.exe C:/Users/Admin/AppData/Local/Programs/Python/Python37-32/Scripts/db_connect.py
Traceback (most recent call last):
  File "C:/Users/Admin/AppData/Local/Programs/Python/Python37-32/Scripts/db_connect.py", line 1, in <module>
    import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

Process finished with exit code 1

我需要测试数据库连接

1 个答案:

答案 0 :(得分:0)

您可以使用try除外,如果连接失败,它将抛出错误并显示错误

import psycopg2


def connect__to_database():
    conn = None
    try:
        conn = psycopg2.connect("dbname=your_db_name user=postgres password=your_db_pass")
        return conn 
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    return False