Python Data Access 简明教程
Python PostgreSQL - Database Connection
PostgreSQL 提供了自己的 shell 来执行查询。要建立与 PostgreSQL 数据库的连接,请确保已将其正确安装在您的系统中。打开 PostgreSQL shell 提示符并传递服务器、数据库、用户名和密码等详细信息。如果您提供的详细信息全部正确,则与 PostgreSQL 数据库建立的连接。
PostgreSQL provides its own shell to execute queries. To establish connection with the PostgreSQL database, make sure that you have installed it properly in your system. Open the PostgreSQL shell prompt and pass details like Server, Database, username, and password. If all the details you have given are appropriate, a connection is established with PostgreSQL database.
在传递详细信息时,您可以使用 shell 建议的默认服务器、数据库、端口和用户名。
While passing the details you can go with the default server, database, port and, user name suggested by the shell.

Establishing connection using python
psycopg2 的连接类表示/处理连接的实例。您可以使用 connect() 函数创建新连接。此函数接受基本连接参数,例如 dbname、user、password、host、port,并返回连接对象。使用此函数,您可以与 PostgreSQL 建立连接。
The connection class of the psycopg2 represents/handles an instance of a connection. You can create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object. Using this function, you can establish a connection with the PostgreSQL.
Example
以下 Python 代码演示如何连接到现有数据库。如果数据库不存在,则它将被创建,最终将返回一个数据库对象。PostgreSQL 的默认数据库名称为 postrgre。因此,我们把它当作数据库名称提供。
The following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. The name of the default database of PostgreSQL is postrgre. Therefore, we are supplying it as the database name.
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',
)