Get rid of double quotation marks with SQLalchemy for PostgreSQL

独自空忆成欢 提交于 2020-05-29 07:12:48

问题


I'm trying to import 200 SAS XPT files to my PostgreSQL database:

engine = create_engine('postgresql://user:pwd@server:5432/dbName')
for file in listdir(dataPath):
    name, ext = file.split('.', 1)
    with open(join(dataPath, file), 'rb') as f:
        xport.to_dataframe(f).to_sql(name, engine, schema='schemaName', if_exists='replace', index=False)
    print("Successfully wrote ", file, " to database.")

However, the SQL generated has double quotation marks for all identifiers, for example: CREATE TABLE "Y2009"."ACQ_F" ("SEQN" FLOAT(53), "ACD010A" FLOAT(53));. The problem is, if the column / table / schema is created with quotation marks, every time I need to query them, I must include the quotation marks as well, at the same time use the exact capitalization.

I want to get rid of quotation marks, while I cannot write custom SQLs myself, because these files each has very different structure.


回答1:


PostgreSQL requires uppercase table / column names to be quoted (reference). That is why identifiers in the SQL constructed by SQLalchemy are quoted. To avoid this, convert the column names of the dataframe to all lowercase:

with open(join(dataPath, file), 'rb') as f:
     data = xport.to_dataframe(f)
     data.columns = map(str.lower, data.columns)
     data.to_sql(name.lower(), engine, schema='y2007')


来源:https://stackoverflow.com/questions/48070409/get-rid-of-double-quotation-marks-with-sqlalchemy-for-postgresql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!