Python-data-access-python-postgresql-database-connection

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

Python PostgreSQL-データベース接続

PostgreSQLはクエリを実行する独自のシェルを提供します。 PostgreSQLデータベースとの接続を確立するには、システムに適切にインストールされていることを確認してください。 PostgreSQLシェルプロンプトを開き、サーバー、データベース、ユーザー名、パスワードなどの詳細を渡します。 指定した詳細がすべて適切な場合、PostgreSQLデータベースとの接続が確立されます。

詳細を渡す際に、デフォルトのサーバー、データベース、ポート、およびシェルによって提案されたユーザー名を使用できます。

PostgreSQLシェルプロンプト

Pythonを使用して接続を確立する

*_psycopg2_* の接続クラスは、接続のインスタンスを表し/処理します。 * connect()*関数を使用して、新しい接続を作成できます。 これは、dbname、user、password、host、portなどの基本的な接続パラメーターを受け入れ、接続オブジェクトを返します。 この関数を使用して、PostgreSQLとの接続を確立できます。

次のPythonコードは、既存のデータベースに接続する方法を示しています。 データベースが存在しない場合は、データベースが作成され、最終的にデータベースオブジェクトが返されます。 PostgreSQLのデフォルトデータベースの名前は_postrgre_です。 したがって、データベース名として提供しています。

import psycopg2

#establishing the connection
conn = psycopg2.connect(
   database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432'
)
#Creating a cursor object using the cursor() method
cursor = conn.cursor()

#Executing an MYSQL function using the execute() method
cursor.execute("select version()")

# Fetch a single row using fetchone() method.
data = cursor.fetchone()
print("Connection established to: ",data)

#Closing the connection
conn.close()
Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)

出力

Connection established to: (
   'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit',
)