问题
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