是否可以在 postgresql 中动态创建 table?
Is it possible to create table in postgresql dynamically?
我正在尝试从 csv 文件创建 postgresql table。问题是,每次我下载 csv 文件时,它都有不同的列集。
我考虑创建具有最大列的 table,从而为没有额外列的报告填充 0。但是我也不知道以后csv文件里会不会有更多的列。
预期:我应该能够在 postgres 数据库中动态创建一个 table,其中包含当天生成的 csv 文件所需的列。
经过一番摸索之后,我想出了一个适合我的解决方案,尽管我担心它不符合优化的编码标准。
关于我想出的方法:
Step 1: Drop the table
cur.execute('''DROP TABLE test;''')
Step 2: Create an empty table
cur.execute('''CREATE TABLE test();''')
Step 3: Add columns along with their datatype in a for loop (As it will be a loop it will take time depending on the size of your report and thus I mentioned this method might not be he best one)
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),))
Step 4:Use copy_from to copy the content from the desired file
with open('.\test.csv', 'r') as f:
next(f) # skip the header row
cur.copy_from(f, 'test', sep=',', columns=df.columns)
我正在尝试从 csv 文件创建 postgresql table。问题是,每次我下载 csv 文件时,它都有不同的列集。
我考虑创建具有最大列的 table,从而为没有额外列的报告填充 0。但是我也不知道以后csv文件里会不会有更多的列。
预期:我应该能够在 postgres 数据库中动态创建一个 table,其中包含当天生成的 csv 文件所需的列。
经过一番摸索之后,我想出了一个适合我的解决方案,尽管我担心它不符合优化的编码标准。
关于我想出的方法:
Step 1: Drop the table
cur.execute('''DROP TABLE test;''')
Step 2: Create an empty table
cur.execute('''CREATE TABLE test();''')
Step 3: Add columns along with their datatype in a for loop (As it will be a loop it will take time depending on the size of your report and thus I mentioned this method might not be he best one)
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),))
Step 4:Use copy_from to copy the content from the desired file
with open('.\test.csv', 'r') as f:
next(f) # skip the header row
cur.copy_from(f, 'test', sep=',', columns=df.columns)