psycopg2.OperationalError:严重:数据库“新闻”不存在

时间:2019-10-06 02:12:37

标签: python postgresql vagrant

尝试建立与我的postgres sql数据库的连接以通过python代码运行查询。

我正在使用MAC(mojave 10.14.6),并试图通过python脚本连接到我的虚拟postgres数据库。我可以通过终端窗口访问数据库,但是当我尝试使用psycopg2连接时,我得到了psycopg2.OperationalError:FATAL:数据库“学生”不存在。

我检查了我只有一个postgres实例,我检查了所用的端口并将其放在参数中。

Postgres版本为11.5 Python版本是python 3.7.4 我已经检查了psql的位置/ usr / local / bin / psql 我已经检查了postgres的位置/ usr / local / bin / postgres

在其他任何帖子中都没有建议的建议。

import psycopg2

#DBNAME = 'students'

def connect():

    print('Trying to connect to server ...')
    conn = psycopg2.connect(dbname = 'students')
    cur = conn.cursor()

    cur.execute('select * from students')


    results = cur.fetchall()
    print(results)

    cur.close
    conn.close

if __name__ == '__main__':
    connect()

---------------------------------------------------------------------

Below works when I connect to the postgres database
-----------------------------------------------------------------------
import psycopg2

def connect():

    print('Trying to connect to server ...')

    conn = psycopg2.connect(dbname = 'postgres')
    cur = conn.cursor()

    print('PostgreSQL database version:')
    cur.execute('select version()')
    db_version = cur.fetchone()
    print(db_version)


    cur.close
    conn.close

if __name__ == '__main__':
    connect()

result:

RESTART: /Users/Karen/Documents/Backup/Karens_Documents/Web_Development/web_dev_nano/course-ud303/SQL/fullstack-nanodegree-vm-master/vagrant/db_test.py 
Trying to connect to server ...
PostgreSQL database version:
('PostgreSQL 11.5 on x86_64-apple-darwin18.6.0, compiled by Apple LLVM version 10.0.1 (clang-1001.0.46.4), 64-bit',)

Error:

Traceback (most recent call last):
  File "/Users/Karen/Documents/Backup/Karens_Documents/Web_Development/web_dev_nano/course-ud303/SQL/fullstack-nanodegree-vm-master/vagrant/db_test.py", line 28, in <module>
    connect()
  File "/Users/Karen/Documents/Backup/Karens_Documents/Web_Development/web_dev_nano/course-ud303/SQL/fullstack-nanodegree-vm-master/vagrant/db_test.py", line 9, in connect
    conn = psycopg2.connect(dbname = DBNAME)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/psycopg2/__init__.py", line 126, in connect
    conn = _connect(dsn, connection_factory=connection_factory, **kwasync)
psycopg2.OperationalError: FATAL:  database "students" does not exist

0 个答案:

没有答案