首页 > 解决方案 > 是否可以在 postgresql 中动态创建表?

问题描述

我正在尝试从 csv 文件创建一个 postgresql 表。问题是,每次我下载 csv 文件时,它都有不同的列集。

我想用最大列创建表,从而为没有额外列的报告填充 0。但我也不知道将来 csv 文件中是否会有更多列。

预期:我应该能够在 postgres 数据库中动态创建一个表,其中包含对应于当天生成的 csv 文件的所需列。

标签: postgresqlcsvcreate-table

解决方案


经过一番摸索后,我想出了一个对我来说很好的解决方案,尽管我担心它不符合优化的编码标准。

关于我设计的方法:

第 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)

推荐阅读