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

使用SQLAlchemy从CSV在PostgreSQL指定Schema建表遇异常及后续问题

更新

根据Adrian Klaver的建议,执行show search_path;后发现搜索路径为"$user", public,在psql中执行set search_path to dbo,public;后,使用\d就能看到预期的表了。目前新问题是在.to_sql(...)调用中设置列类型时出现内存相关报错,求相关解决方案提示。


原问题

我正在编写自动化脚本,从CSV文件创建PostgreSQL表。本人对SQL、PostgreSQL和pandas都非常陌生,实现方式可能不够高效。

注意: 虽然提到了一个奇怪的错误,但核心问题是表根本看不到!

操作步骤

  1. 在psql中创建数据库和schema(已提前创建用户porter_test2):
postgres=# create database porter_test2;
postgres=# grant all privileges on database porter_test2 to porter_test2;
postgres=# \c porter_test2;
porter_test2=# create schema dbo;
porter_test2=# grant all on schema dbo to porter_test2;

执行\dn确认dbo schema已创建(默认schema为public)。

  1. 用Python脚本尝试在dbo schema中创建表:
import pandas as pd
from sqlalchemy import create_engine

engine = create_engine('postgresql://porter_test2:[my_password]@localhost:5432/porter_test2')

file_list = ["table1.csv"]

for file in file_list:
    df=pd.read_csv(file)
    table_name = file[:-4]
    df.to_sql(con=engine, name=table_name, schema = 'dbo')

问题现象

  • 第一次运行脚本无报错无输出,但psql中执行\d显示Did not find any relations.
  • 再次运行脚本报错:
ValueError: Table 'table1' already exists.

但\d还是看不到表

  • 添加if_exists='replace'参数后,脚本无报错,但依旧看不到表

需求

希望用Python脚本把指定CSV文件列表创建为同名表,存储到指定PostgreSQL数据库的dbo schema中,后续能通过... FROM dbo.table1 ...查询访问这些表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 00:35:11