Python Postgresql 简明教程

Python PostgreSQL - Create Database

你可以使用 CREATE DATABASE 语句在 PostgreSQL 中创建一个数据库。你可以通过在命令后指定要创建的数据库的名称,在 PostgreSQL shell 提示符中执行此语句。

Syntax

以下是 CREATE DATABASE 语句的语法。

CREATE DATABASE dbname;

Example

以下语句在 PostgreSQL 中创建一个名为 testdb 的数据库。

postgres=# CREATE DATABASE testdb;
CREATE DATABASE

你可以使用 \l 命令列出 PostgreSQL 中的数据库。如果你验证了数据库列表,则可以找到新创建的数据库,如下所示:

postgres=# \l
                                                List of databases
   Name    | Owner    | Encoding |        Collate             |     Ctype   |
-----------+----------+----------+----------------------------+-------------+
mydb       | postgres | UTF8     | English_United States.1252 | ........... |
postgres   | postgres | UTF8     | English_United States.1252 | ........... |
template0  | postgres | UTF8     | English_United States.1252 | ........... |
template1  | postgres | UTF8     | English_United States.1252 | ........... |
testdb     | postgres | UTF8     | English_United States.1252 | ........... |
(5 rows)

你还可以使用命令提示符中的命令 createdb(CREATE DATABASE SQL 语句的包装器)在 PostgreSQL 中创建一个数据库。

C:\Program Files\PostgreSQL\11\bin> createdb -h localhost -p 5432 -U postgres sampledb
Password:

Creating a Database Using Python

psycopg2 的游标类提供了各种方法来执行各种 PostgreSQL 命令、获取记录和复制数据。你可以使用 Connection 类的 cursor() 方法创建一个游标对象。

此类的 execute() 方法接受 PostgreSQL 查询作为参数并执行它。

因此,要在 PostgreSQL 中创建一个数据库,请使用此方法执行 CREATE DATABASE 查询。

Example

以下 python 示例在 PostgreSQL 数据库中创建了一个名为 mydb 的数据库。

import psycopg2

#establishing the connection

conn = psycopg2.connect(
   database="postgres", user='postgres', password='password',
   host='127.0.0.1', port= '5432'
)
conn.autocommit = True

#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Preparing query to create a database
sql = '''CREATE database mydb''';

#Creating a database
cursor.execute(sql)
print("Database created successfully........")

#Closing the connection
conn.close()

Output

Database created successfully........