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

如何通过pandas df.to_sql()向已创建的数据库表插入数据

解决df.to_sql()向已创建PostgreSQL表插入无数据的问题

我看到你遇到的困扰:手动创建PostgreSQL表后,用df.to_sql()插入数据时没报错,但数据就是没进表,而让SQLAlchemy自动建表却能正常插入。下面是几个核心问题排查和对应的解决方案:

1. 先修正建表语句的语法错误

你的建表SQL里有个明显的笔误:apparel_category" TEXT, 这一行缺少了开头的双引号,正确写法应该是"apparel_category" TEXT,。这个错误会导致表结构异常——要么表创建时隐含失败(但PostgreSQL可能静默处理成不带引号的列名),要么最终表的列名和DataFrame里的列名无法匹配,导致插入时数据找不到对应列,悄无声息地“丢失”。

2. 统一用SQLAlchemy处理所有数据库操作

你混合使用了psycopg2的conn/cur和SQLAlchemy的engine,这两个连接可能处于不同的事务上下文。即便你执行了conn.commit(),SQLAlchemy的连接可能无法识别到新创建的表状态,或者插入操作的事务没有正确提交。

建议全程用SQLAlchemy处理表创建和数据插入,保持连接一致性:

from sqlalchemy import create_engine
import pandas as pd
import csv
import sys

# 初始化SQLAlchemy引擎
engine = create_engine('postgresql://postgres:Shubham@123@localhost:5432/walmart')

# 修正后的建表语句
create_query = '''create table if not exists new_table(
"item_id" TEXT,
"product_id" TEXT,
"abstract_product_id" TEXT,
"product_name" TEXT,
"product_type" TEXT,
"ironbank_category" TEXT,
"primary_shelf" TEXT,
"apparel_category" TEXT,
"brand" TEXT)'''

# 用SQLAlchemy执行建表并提交
with engine.connect() as conn:
    conn.execute(create_query)
    conn.commit()

file_name = 'new_table'
new_file = "C:\\Users\\shubham.shinde\\Desktop\\wallll\\new_file.txt"

# 读取TSV数据(保持原参数)
data = pd.read_csv(new_file, delimiter="\t", chunksize=500000, error_bad_lines=False, quoting=csv.QUOTE_NONE, dtype="unicode", iterator=True)

with open(file_name + '_bad_rows.txt', 'w') as f1:
    sys.stderr = f1
    for df in data:
        # 加入index=False,避免把DataFrame索引当作列插入
        df.to_sql('new_table', engine, if_exists='append', index=False)
data.close()

3. 确认列名完全匹配(包括大小写)

PostgreSQL中,用双引号定义的列名是大小写敏感的。请检查你的DataFrame列名和表的列名是否完全一致——比如DataFrame里的列是item_id还是Item_ID,必须和表的列名大小写完全对应,否则插入时会因列不匹配无法写入数据(且默认不会触发报错)。

4. 加入日志验证插入过程

你可以在循环中加入打印语句,确认每个数据块是否有数据,以及插入后的表行数变化,帮你定位问题节点:

for i, df in enumerate(data):
    print(f"正在处理第{i}个数据块,包含{len(df)}行数据")
    df.to_sql('new_table', engine, if_exists='append', index=False)
    # 验证插入后的总行数
    with engine.connect() as conn:
        row_count = conn.execute("select count(*) from new_table").scalar()
        print(f"插入后表内总行数:{row_count}\n")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:25:53