You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Pandas构建的DataFrame数据表保存至数据库?

把Pandas DataFrame保存到数据库的实现方法

Pandas自带的to_sql方法可以轻松把DataFrame写入数据库,核心依赖SQLAlchemy来管理数据库连接,下面分不同数据库场景说明具体操作:

第一步:安装必要依赖

先安装SQLAlchemy(所有场景通用):

pip install sqlalchemy

1. 保存到SQLite(轻量本地数据库,无需额外服务)

SQLite是文件型数据库,不用搭建服务器,适合小型项目或快速测试:

import pandas as pd
from sqlalchemy import create_engine

# 你的原有数据构建代码
employees = {'Name of Machining': ['milling','Drilling','Drilling','Chamfering'],
             'Speed': [275,275,275,275],
             'Feed': [0.28,0.03,0.03,0.28],
             'Tool': ['EndMill','TwistDrill','TwistDrill','EndMill']
            }
df = pd.DataFrame(employees, columns= ['Name of Machining','Speed','Feed','Tool'])

# 创建SQLite连接,'machining.db'是生成的本地数据库文件名
engine = create_engine('sqlite:///machining.db')

# 将DataFrame写入名为'machining_operations'的表
# if_exists参数:replace=覆盖现有表,append=追加数据,fail=表存在则报错
# index=False:不把DataFrame的索引存成数据库列
df.to_sql('machining_operations', engine, if_exists='replace', index=False)

# 可选:验证数据是否写入成功
read_back_df = pd.read_sql('SELECT * FROM machining_operations', engine)
print(read_back_df)

2. 保存到MySQL数据库

需要先安装MySQL驱动,二选一即可:

# 方案1:mysql-connector-python
pip install mysql-connector-python
# 方案2:pymysql
pip install pymysql

然后编写代码:

import pandas as pd
from sqlalchemy import create_engine

# 你的DataFrame构建代码不变

# 替换成你的MySQL实际配置:用户名、密码、主机、目标数据库名
# 驱动对应你安装的包,mysqlconnector或pymysql
engine = create_engine('mysql+mysqlconnector://root:your_password@localhost/your_database_name')

# 写入数据库
df.to_sql('machining_operations', engine, if_exists='replace', index=False)

3. 保存到PostgreSQL数据库

先安装PostgreSQL驱动:

pip install psycopg2-binary

代码示例:

import pandas as pd
from sqlalchemy import create_engine

# 你的DataFrame构建代码不变

# 替换成你的PostgreSQL实际配置
engine = create_engine('postgresql+psycopg2://postgres:your_password@localhost/your_database_name')

# 写入数据库
df.to_sql('machining_operations', engine, if_exists='replace', index=False)

关键参数说明

  • if_exists:控制表存在时的行为,常用值:
    • replace:删除原有表并重新创建写入
    • append:在现有表后追加数据
    • fail:如果表已存在则抛出错误
  • index:默认True,设为False避免把DataFrame的索引列写入数据库
  • dtype:可选参数,手动指定列的数据类型,比如解决自动推断类型不准确的问题:
    from sqlalchemy import Integer, Float, String
    df.to_sql(
        'machining_operations',
        engine,
        if_exists='replace',
        index=False,
        dtype={
            'Name of Machining': String(50),
            'Speed': Integer(),
            'Feed': Float(),
            'Tool': String(50)
        }
    )
    

内容的提问来源于stack exchange,提问作者Sujansujarine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:27:30