Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python postgresql

作者:血染胸毛   发布日期:2025-08-11   浏览:14

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)

解释说明:

  1. 导入模块:使用 psycopg2 模块来与 PostgreSQL 数据库进行交互。
  2. 连接数据库:定义 connect_to_db 函数,用于创建与 PostgreSQL 数据库的连接。需要提供用户名、密码、主机地址、端口和数据库名称。
  3. 插入数据:定义 insert_data 函数,用于将数据插入指定的表中。该函数接收连接对象、表名和要插入的数据字典作为参数。
  4. 查询数据:定义 query_data 函数,用于从指定表中查询所有数据并打印出来。
  5. 关闭连接:定义 close_connection 函数,用于关闭数据库连接。
  6. 主程序:在 __main__ 中演示如何使用上述函数,包括连接数据库、插入数据、查询数据和关闭连接。

希望这段代码能帮助你理解如何使用 Python 和 PostgreSQL 进行基本的数据库操作。

上一篇:python中map

下一篇:python json库

大家都在看

python时间格式

python开发windows应用程序

python中len是什么意思

python ord和chr

python中的yield

python自定义异常

python判断路径是否存在

python list.pop

python的for i in range

npm config set python

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站