避免同一数据的多个条目进入数据库表(Python)

2024-05-15 23:47:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在将Python(一个数据帧)中的信息写到SQLite数据库中的不同表中。我目前正在测试我的数据帧中的“单元格”与数据库中某个表的名称是否匹配,如果匹配,则将相关行中的信息从数据帧发送到该表。参见以下代码:

    for ii in range(0,row_count):
        df_area= pon_transpose.index[ii]
        export_date= pon_transpose.iloc[ii,0]
        export_morning= pon_transpose.iloc[ii,1]
        export_day= pon_transpose.iloc[ii,2]
        export_eve= pon_transpose.iloc[ii,3]
        export_night= pon_transpose.iloc[ii,4]
        cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
        available_tables=[item[0] for item in cur.fetchall()]        # list of strings of all the table names in the database
        list_len= len(available_tables)
        for iii in range (0, list_len):
            if (re.match('\w*'+df_area, available_tables[iii])):
                relevant_table=available_tables[iii]
                cur.execute("INSERT INTO " + relevant_table + " VALUES (?,?,?,?,?)", (export_date, export_morning, export_day, export_eve, export_night))
                con.commit()
            iii=iii+1
        ii=ii+1

以上只是我代码的一部分,位于另一个循环中。这导致Python中的信息被多次读入数据库表,这是我想要避免的。为了避免这种情况,我尝试将上述代码中的最后4行更改为:

cur.execute("INSERT OR IGNORE INTO " + relevant_table + " VALUES (?,?,?,?,?)", (export_date, export_morning, export_day, export_eve, export_night))

以及:

cur.execute("INSERT OR REPLACE INTO " + relevant_table + " VALUES (?,?,?,?,?)", (export_date, export_morning, export_day, export_eve, export_night))

然而,到目前为止,这种做法并不成功。我有一种感觉,我应该能够做到这一点与“插入或替换”,但现在这个修改是没有做任何事。有没有人有什么想法或能发现任何错误?我对SQLite语言不太熟悉,所以也许我找不到一个简单的语法修复来解决我的问题(尽管我已经研究过了)。你知道吗

让我知道我的代码/附加信息的任何特定输出是否有帮助。你知道吗

先谢谢你。你知道吗


Tags: 代码in信息datetableexporteveiii