经过一番摸索,我想出了一个适合我的解决方案,尽管我担心它不符合优化的编码标准。
关于我设计的方法:
第 1 步:删除表
cur.execute('''DROP TABLE test;''')
第二步:创建一个空表
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)