python建立数据库_Python PostgreSQL-创建数据库

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

句法

以下是CREATE DATABASE语句的语法。

CREATE DATABASE dbname;

以下语句在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(围绕SQL语句CREATE DATABASE的包装器)从命令提示符在PostgreSQL中创建数据库。

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

Password:

使用python创建数据库

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

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

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

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

importpsycopg2#establishing the connectionconn=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() methodcursor=conn.cursor()#Preparing query to create a databasesql='''CREATE database mydb''';#Creating a databasecursor.execute(sql)print("Database created successfully........")#Closing the connectionconn.close()

输出量

Database created successfully........

你可能感兴趣的:(python建立数据库)