0
我有一個python腳本將文件上傳到Postgres數據庫服務器。這些文件然後被轉換爲SQL表。爲此,我使用SQLalchemy庫。如何在Postgres + SQLalchemy中的列名太長時引發異常?
問題出在列名太長時出現。我不希望Postgres在超過最大長度時自動截斷列名(如果我正確記得,它在Postgres中是63)。表格最後有列名不明的名稱,我只想讓腳本取消上傳。
顯而易見的解決方案是在我的腳本中只是「硬編碼」最大長度,如果有人試圖上傳帶有「太長」列名的表,就引發異常。不過,我認爲這應該可以在SQLalchemy中配置,例如,當表名已在數據庫中使用時引發異常。從我的腳本
提取上傳表:
from SQLalchemy import (
create_engine,
)
import pandas as pd
DB_CONFIG_DICT = {
'user': "user",
'host': "urlforhost.com",
'port': 5432,
'password': "password"
}
DB_CONN_FORMAT = "postgresql+psycopg2://{user}:{password}@{host}:{port}/{database}"
DB_CONN_URI_DEFAULT = (DB_CONN_FORMAT.format(database='sandbox', **DB_CONFIG_DICT))
engine = create_engine(DB_CONN_URI_DEFAULT)
path = "file.csv"
table_name = "table_name"
df = pd.read_csv(path, decimal=r".")
df.columns = [c.lower() for c in df.columns] #postgres doesn't like capitals or spaces
df.to_sql(table_name, engine)
謝謝,但這正是我試圖避免做的。 – Alechan