📜  Python PostgreSQL-数据库连接

📅  最后修改于: 2020-11-07 08:50:15             🧑  作者: Mango


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

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

PostgreSQL Shell提示

使用Python建立连接

psycopg2的连接类表示/处理连接的实例。您可以使用connect()函数创建新的连接。这接受基本的连接参数,例如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',
)