Pandas+sqlalchemy+PostgresSQL能很方便的进行数据库访问。在使用Pandas导入csv数据直接转换为PostgresSQL的Table遇见了大小写问题。
from sqlalchemy import create_engine, text
import pandas as pd
try:
engine = create_engine('postgresql://postgres:xxxxxx@localhost:5432/assignment')
except Exception as e:
print("Unable to connect to the database.")
print(e)
conn = engine.connect()
df = pd.read_csv("Test.csv")
df.to_sql("Test",con=engine,if_exists='replace',index=False)
在PostgreSQL数据库中会发现Test的数据库,但是你使用下面的SQL语句会告诉你Table不存在。
SELECT * FROM Test
你必须使用public."Test"才可以使用。
SELECT * from public."Test"
这是因为你的Table名中包含了大写字符,PostgresSQL需要区分大小写的table名导致的。
将df.to_sql中的table名用全小写就能解决这个问题。
df.to_sql("test",con=engine,if_exists='replace',index=False)
SELECT * FROM test
文章讲述了如何使用Pandas和SQLAlchemy连接PostgreSQL数据库时遇到的大小写敏感性问题,以及如何通过将表名全部转换为小写来解决Table不存在的错误。
2026

被折叠的 条评论
为什么被折叠?



