1

我有这段代码可以将 Excel 数据导入 SQLlite,但想知道如何将其导入 SQLAlchemy,而不需要手动命名字段。

我不确定如何从 SQLAlchemy 中的 Excel 列字段自动创建字段和架构。

con = sqlite3.connect('test237.db')
wb = load_workbook(filename=r'test.xlsx')
sheets = wb.get_sheet_names()

for sheet in sheets:
    ws = wb[sheet] 
    columns= []
    query = 'CREATE TABLE ' + str(sheet) + '(ID INTEGER PRIMARY KEY AUTOINCREMENT'
    for row in ws.rows[0]:
        query += ', ' + row.value + ' TEXT'
        columns.append(row.value)
    query += ');'

    con.execute(query)

    tup = []
    for i, rows in enumerate(ws):
        tuprow = []
        for row in rows:
            tuprow.append(unicode(row.value).strip()) if unicode(row.value).strip() != 'None' else tuprow.append('')
        tup.append(tuple(tuprow))


    insQuery1 = 'INSERT INTO ' + str(sheet) + '('
    insQuery2 = ''
    for col in columns:
        insQuery1 += col + ', '
        insQuery2 += '?, '
    insQuery1 = insQuery1[:-2] + ') VALUES('
    insQuery2 = insQuery2[:-2] + ')'
    insQuery = insQuery1 + insQuery2

    con.execute(insQuery, tup)
con.close()
4

0 回答 0