Python PostgreSQL 数据库连接


PostgreSQL 提供了自己的 shell 来执行查询。要建立与 PostgreSQL 数据库的连接,请确保已在系统中正确安装它。打开 PostgreSQL shell 提示并传递服务器、数据库、用户名和密码等详细信息。如果你提供的所有详细信息都合适,则与 PostgreSQL 数据库建立连接。

在传递详细信息时,你可以使用 shell 建议的默认服务器、数据库、端口和用户名。

PostgreSQL Shell Prompt

使用python建立连接


的连接类 psycopg2 表示/处理连接的实例。你可以使用 连接() 功能。这接受基本的连接参数,如 dbname、用户、密码、主机、端口并返回一个连接对象。使用此功能,你可以建立与 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',
)