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)
相关推荐
憨憨小白几秒前
Python 的集合类型
开发语言·python·青少年编程·少儿编程
白杆杆红伞伞5 分钟前
01_快速入门
python·pandas
q5673152312 分钟前
如何在Django中创建新的模型实例
数据库·python·线性代数·django·sqlite
学步_技术1 小时前
Python编码系列—Python团队开发工作流:高效协作的艺术
开发语言·python·团队开发
shiming88792 小时前
Python数据分析与可视化
开发语言·python·数据分析
William数据分析2 小时前
Python数据分析与可视化实战指南
python·数据
Python之栈2 小时前
Python if 语句优化技巧
python·算法
姑苏老陈2 小时前
【Python基础】Python文件处理
开发语言·python·python文件操作
yukai080082 小时前
Python 全栈系列271 微服务踩坑记
python·微服务·php
学步_技术3 小时前
Python编码系列—Python工厂方法模式:构建灵活对象的秘诀
开发语言·python·工厂方法模式