MST

星途 面试题库

面试题:Python中如何使用psycopg2库连接PostgreSQL数据库并执行简单查询

请使用Python的psycopg2库,编写代码连接到一个PostgreSQL数据库,数据库信息如下:主机地址为'localhost',端口为5432,数据库名称为'test_db',用户名'user',密码'password'。连接成功后,执行一个简单的查询,例如从名为'employees'的表中选择所有列,并打印结果。
27.9万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
import psycopg2

try:
    # 连接到PostgreSQL数据库
    connection = psycopg2.connect(
        host='localhost',
        port=5432,
        database='test_db',
        user='user',
        password='password'
    )

    # 创建游标对象
    cursor = connection.cursor()

    # 执行查询
    query = "SELECT * FROM employees"
    cursor.execute(query)

    # 获取所有结果
    results = cursor.fetchall()

    # 打印结果
    for row in results:
        print(row)

    # 关闭游标和连接
    cursor.close()
    connection.close()

except (Exception, psycopg2.Error) as error:
    print("连接数据库或执行查询时出错:", error)