- Python PostgreSQL 教程
- Python PostgreSQL - 主页
- Python PostgreSQL - 简介
- Python PostgreSQL - 数据库连接
- Python PostgreSQL - 创建数据库
- Python PostgreSQL - 创建表
- Python PostgreSQL - 插入数据
- Python PostgreSQL - 选择数据
- Python PostgreSQL -Where 子句
- Python PostgreSQL - 排序依据
- Python PostgreSQL - 更新表
- Python PostgreSQL - 删除数据
- Python PostgreSQL - 删除表
- Python PostgreSQL - 限制
- Python PostgreSQL - 加入
- Python PostgreSQL - 游标对象
- Python PostgreSQL 有用资源
- Python PostgreSQL - 快速指南
- Python PostgreSQL - 有用的资源
- Python PostgreSQL - 讨论
Python PostgreSQL - 数据库连接
PostgreSQL 提供了自己的 shell 来执行查询。要与 PostgreSQL 数据库建立连接,请确保您已在系统中正确安装它。打开 PostgreSQL shell 提示符并传递服务器、数据库、用户名和密码等详细信息。如果您提供的所有详细信息均正确,则会与 PostgreSQL 数据库建立连接。
在传递详细信息时,您可以使用 shell 建议的默认服务器、数据库、端口和用户名。
使用Python建立连接
psycopg2的连接类表示/处理连接的实例。您可以使用connect()函数创建新连接。它接受基本连接参数,例如数据库名、用户、密码、主机、端口并返回连接对象。使用该函数,您可以与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', )