Python 使用 psycopg2 创建 postgresql 数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19426448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:42:57  来源:igfitidea点击:

Creating a postgresql DB using psycopg2

pythonpostgresqlpsycopg2

提问by nish

I'm trying to create a postgres DB using a python script. Some research showed that using the psycopg2 module might be a way to do it. I installed it and made the required changes in the pg_hba.conffile. I used the following code to create the DB:

我正在尝试使用 python 脚本创建一个 postgres 数据库。一些研究表明,使用 psycopg2 模块可能是一种方法。我安装了它并在pg_hba.conf文件中进行了所需的更改。我使用以下代码创建数据库:

#!/usr/bin/python
# -*- coding: utf-8 -*-

from psycopg2 import connect
import sys
from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMIT

con = None
con = connect(user='****', host = 'localhost', password='****')

dbname = "voylla_production1710"

con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = con.cursor()
cur.execute('CREATE DATABASE ' + dbname)
cur.close()
con.close()

I tried replacing con = connect(user='nishant', host = 'localhost', password='everything')with con = connect(user='nishant', password='everything')

我试图取代con = connect(user='nishant', host = 'localhost', password='everything')con = connect(user='nishant', password='everything')

But I'm getting the following Error:

但我收到以下错误:

con = connect(user='nishant', host = 'localhost', password='everything') 
 File "/usr/lib/python2.7/dist-packages/psycopg2/__init__.py", line 179, in connect
connection_factory=connection_factory, async=async)
 psycopg2.OperationalError: FATAL:  database "nishant" does not exist

Could someone please tell me the right way of doing it. Thanks

有人可以告诉我正确的做法。谢谢

采纳答案by Nicolas

PostgreSQL's client connects to a database named after the user by default. This is why you get the error FATAL: database "nishant" does not exist.

默认情况下,PostgreSQL 的客户端连接到以用户命名的数据库。这就是您收到错误 FATAL: 的原因 database "nishant" does not exist

You can connect to the default system database postgresand then issue your query to create the new database.

您可以连接到默认系统数据库postgres,然后发出查询以创建新数据库。

con = connect(dbname='postgres', user='nishant', host='localhost', password='everything')

Make sure your nishantuser has permission to create databases.

确保您的nishant用户有权创建数据库。

Edit: By the way, check out the ~/.pgpass file to store password securely and not in the source code (http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html). libpq, the postgresql client librairy, check for this file to get proper login information. It's very very handy.

编辑:顺便说一下,检查 ~/.pgpass 文件以安全地存储密码而不是源代码(http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html)。libpq,postgresql 客户端库,检查这个文件以获得正确的登录信息。它非常非常方便。