使用psycopg2创建一个Postgresql数据库 [英] Creating a postgresql DB using psycopg2

查看:527
本文介绍了使用psycopg2创建一个Postgresql数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.conf file. I used the following code to create the DB:

#!/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()

我尝试替换 con = connect(user ='nishant',host = 'localhost',password ='everything') with con = connect(user ='nishant',password ='everything')

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') 
 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

推荐答案

PostgreSQL的客户端默认连接到以用户命名的数据库。
这就是为什么您收到错误致命信息的原因:数据库 nishant不存在

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.

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

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

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

确保您的修饰剂用户具有创建数据库的权限。

Make sure your nishant user has permission to create databases.

编辑:顺便说一句,请检出〜/ .pgpass文件以安全地存储密码,而不是在源代码中存储密码( http://www.postgresql.org/docs/9.2/static/libpq-pgpass.html )。 libpq,PostgreSQL客户端库,请检查该文件以获取正确的登录信息。非常方便。

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.

这篇关于使用psycopg2创建一个Postgresql数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆