import psycopg2
# 连接到 PostgreSQL 数据库
def connect_to_db():
    try:
        # 创建连接对象
        connection = psycopg2.connect(
            user="your_username",
            password="your_password",
            host="127.0.0.1",
            port="5432",
            database="your_database"
        )
        return connection
    except (Exception, psycopg2.Error) as error:
        print("Error while connecting to PostgreSQL", error)
        return None
# 插入数据到表中
def insert_data(connection, table_name, data):
    try:
        cursor = connection.cursor()
        placeholders = ', '.join(['%s'] * len(data))
        columns = ', '.join(data.keys())
        sql = f"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})"
        cursor.execute(sql, list(data.values()))
        connection.commit()
        print(f"Record inserted successfully into {table_name} table")
    except (Exception, psycopg2.Error) as error:
        print("Failed to insert record into table", error)
# 查询数据
def query_data(connection, table_name):
    try:
        cursor = connection.cursor()
        postgreSQL_select_Query = f"select * from {table_name}"
        cursor.execute(postgreSQL_select_Query)
        records = cursor.fetchall()
        print(f"Total rows are:  {len(records)}")
        for row in records:
            print(row)
    except (Exception, psycopg2.Error) as error:
        print("Error while fetching data from PostgreSQL", error)
# 断开数据库连接
def close_connection(connection):
    if connection:
        connection.close()
        print("PostgreSQL connection is closed")
# 示例代码
if __name__ == "__main__":
    connection = connect_to_db()
    if connection:
        # 插入示例数据
        data = {
            'id': 1,
            'name': 'John Doe',
            'age': 30
        }
        insert_data(connection, 'employees', data)
        # 查询数据
        query_data(connection, 'employees')
        # 关闭连接
        close_connection(connection)psycopg2 模块来与 PostgreSQL 数据库进行交互。connect_to_db 函数,用于创建与 PostgreSQL 数据库的连接。需要提供用户名、密码、主机地址、端口和数据库名称。insert_data 函数,用于将数据插入指定的表中。该函数接收连接对象、表名和要插入的数据字典作为参数。query_data 函数,用于从指定表中查询所有数据并打印出来。close_connection 函数,用于关闭数据库连接。__main__ 中演示如何使用上述函数,包括连接数据库、插入数据、查询数据和关闭连接。希望这段代码能帮助你理解如何使用 Python 和 PostgreSQL 进行基本的数据库操作。
下一篇:python json库
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站