Python-data-access-python-postgresql-create-database

提供:Dev Guides
移動先:案内検索

Python PostgreSQL-データベースの作成

CREATE DATABASEステートメントを使用して、PostgreSQLにデータベースを作成できます。 コマンドの後に作成されるデータベースの名前を指定することにより、PostgreSQLシェルプロンプトでこのステートメントを実行できます。

構文

以下は、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)

SQLステートメントCREATE DATABASEのラッパーである_createdb_コマンドを使用して、コマンドプロンプトから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という名前のデータベースを作成します。

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

出力

Database created successfully........