import psycopg2
# 连接到 PostgreSQL 数据库
def connect_to_postgresql():
try:
# 建立连接
connection = psycopg2.connect(
user="your_username", # 替换为你的数据库用户名
password="your_password", # 替换为你的数据库密码
host="127.0.0.1", # 数据库主机地址,本地则为 127.0.0.1
port="5432", # PostgreSQL 默认端口是 5432
database="your_database" # 替换为你的数据库名称
)
# 创建游标对象
cursor = connection.cursor()
# 打印 PostgreSQL 版本信息(测试连接是否成功)
cursor.execute("SELECT version();")
db_version = cursor.fetchone()
print(f"Connected to PostgreSQL: {db_version}")
# 关闭游标和连接
cursor.close()
connection.close()
except (Exception, psycopg2.Error) as error:
print(f"Error while connecting to PostgreSQL: {error}")
# 调用函数
connect_to_postgresql()
psycopg2 是 Python 中用于连接 PostgreSQL 数据库的库。psycopg2.connect() 方法连接到 PostgreSQL 数据库。你需要提供数据库的用户名、密码、主机地址、端口和数据库名称。connection.cursor() 创建一个游标对象,用于执行 SQL 查询。cursor.execute() 方法执行 SQL 查询,这里我们查询的是 PostgreSQL 的版本信息。cursor.fetchone() 获取查询结果,并打印出来。try-except 块捕获并处理可能的异常,确保程序不会因错误而崩溃。上一篇:def python
下一篇:python 加载json文件
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站