Python 用pandas连接Postgresql库

pandas确实蛮强的,记录使用的代码

python 复制代码
from sqlalchemy import create_engine
import pandas as pd
import os

# 从环境变量中读取数据库连接信息
user = os.getenv('DB_USER', 'xxx')              # 数据库用户名
password = os.getenv('DB_PASSWORD', 'xxx')      # 数据库密码
host = os.getenv('DB_HOST', '192.168.0.1')      # 数据库主机地址
port = os.getenv('DB_PORT', '5432')             # 数据库端口
dbname = os.getenv('DB_NAME', 'xxx')            # 数据库名称

# 创建数据库引擎
# 这个引擎将用于与 PostgreSQL 数据库建立连接
engine = create_engine(f'postgresql://{user}:{password}@{host}:{port}/{dbname}')

# 插入数据到数据库
def insert_data(df):
    """
    将 DataFrame 插入到数据库表中。

    参数:
    df (pd.DataFrame): 要插入的 DataFrame 数据
    """
    df.to_sql(name='employees', 
              schema='xxx',        # 库名
              con=engine, 
              if_exists='append',  # 追加数据到现有表
              index=False)         # 不写入 DataFrame 的索引列

# 查询数据库中的数据
def query_data():
    """
    从数据库中查询数据并返回 DataFrame。

    返回:
    pd.DataFrame: 查询结果 DataFrame
    """
    query = "SELECT * FROM xxx.employees"
    return pd.read_sql_query(query, con=engine)

# 主程序
if __name__ == '__main__':
    # 创建一个 DataFrame,包含要插入的新数据
    df = pd.DataFrame({
        'id': [14, 25, 36],                 # ID 列
        'name': ['Alice', 'Bob', 'Charlie'], # 名字列
        'age': [25, 30, 35],                # 年龄列
        'department': ['HR', 'Engineering', 'Marketing']  # 部门列
    })

    # 将数据插入到数据库中
    insert_data(df)
    
    # 查询并打印数据库中的数据
    df_result = query_data()
    print(df_result)
相关推荐
aqi002 小时前
15天学会AI应用开发(八)使用向量数据库实现RAG功能
人工智能·python·大模型·ai编程·ai应用
Csvn3 小时前
`functools.lru_cache` —— 一行代码搞定缓存加速
后端·python
金銀銅鐵19 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup111 天前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi001 天前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵1 天前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent