postgresql - 是否可以在 postgresql 中动态创建表?
问题描述
我正在尝试从 csv 文件创建一个 postgresql 表。问题是,每次我下载 csv 文件时,它都有不同的列集。
我想用最大列创建表,从而为没有额外列的报告填充 0。但我也不知道将来 csv 文件中是否会有更多列。
预期:我应该能够在 postgres 数据库中动态创建一个表,其中包含对应于当天生成的 csv 文件的所需列。
解决方案
经过一番摸索后,我想出了一个对我来说很好的解决方案,尽管我担心它不符合优化的编码标准。
关于我设计的方法:
第 1 步:删除表
cur.execute('''DROP TABLE test;''')
步骤 2:创建一个空表
cur.execute('''CREATE TABLE test();''')
第 3 步:在 for 循环中添加列及其数据类型(因为这将是一个循环,需要时间取决于报告的大小,因此我提到这种方法可能不是最好的方法)
column_list = list(df.columns)
query = "ALTER TABLE test ADD COLUMN %s;"
for j in range(len(column_list)):
column_name = column_list[j]
if df[column_list].dtypes[j] == 'object':
datatype = 'varchar'
elif df[column_list].dtypes[j] == 'float':
datatype = 'real'
elif report_df[column_list].dtypes[j] == 'int':
datatype = 'int'
elif df[column_list].dtypes[j] == 'bool':
datatype = 'boolean'
column = column_name + " " + datatype
cur.execute(query, (AsIs(column),))
第 4 步:使用 copy_from 从所需文件中复制内容
with open('.\test.csv', 'r') as f:
next(f) # skip the header row
cur.copy_from(f, 'test', sep=',', columns=df.columns)
推荐阅读
- css - 使用 flex 时稍微偏离中心
- python-3.x - Python 日志记录,仅在尚未设置时设置 basicConfig
- ios - 动画 UIImageView 逐行出现在屏幕上
- javascript - 从 InDesign 文件中删除所有语言标签
- nginx - Slim NGINX 重写 URL 以看起来更好
- c# - MS Graph API 返回 400 错误请求
- java - JPA - SortedSet 需要 OrderBy
- hyperledger-fabric - 如何在超级账本 1.4 中使用 queryTransaction() 方法?
- r - 如何从 AWS 地图的页面源中提取经纬度坐标?
- reactjs - --runInBand 导致开玩笑测试失败的常见原因是什么?