簡體   English   中英

Pandas to_sql 在附加到 sqlite 表時忽略外鍵約束?

[英]Pandas to_sql ignores foreign key constrains when appending to sqlite table?

我使用 pandas 方法to_sql到 append DataFrame 到一些 sqlite 表。 sqlite 表在 pandas 應該考慮的列id_region上有一個外鍵約束。 id_region的可用值為 1、2。

如果 DataFrame 包含一個不存在的id_region值 3,我希望to_sql拋出異常。

但是,數據無一例外地寫入數據庫,忽略了外鍵約束。

如果我使用 Navicat 手動更改 sqlite 數據庫中的值,例如更改為 1 然后再更改為 3,我會得到預期的錯誤。

=> sqlite 中的外鍵約束似乎有效,但在插入數據時無效。

=> 如何告訴 pandas 考慮外鍵約束?

重現問題的示例代碼:

import sqlite3
import pandas as pd

file_path = 'demo.sqlite'

id_region = pd.DataFrame([
    {'id': 1, 'label': 'foo'},
    {'id': 2, 'label': 'baa'},
])
id_region.set_index(['id'], inplace=True)

data = pd.DataFrame([
    {'id': 1, 'id_region': 3, 'value': 1}
])
data.set_index(['id'], inplace=True)

create_data_table_query = 'CREATE TABLE `data` (' +\
               'id integer PRIMARY KEY NOT NULL, ' +\
               'id_region integer NOT Null, ' +\
               'value real NOT NULL, ' + \
               'FOREIGN KEY (id_region) REFERENCES id_region(id)' + \
               ')'

with sqlite3.connect(file_path) as connection:
    id_region.to_sql('id_region', connection, index_label='id')

    cursor = connection.cursor()
    cursor.execute(create_data_table_query )
    data.to_sql('data', connection, index_label='id', if_exists='append')

上面代碼創建的表:

id_region

在此處輸入圖像描述

數據,引用 id_region:

在此處輸入圖像描述

在此處輸入圖像描述

必須為 sqlite3 中的每個連接顯式啟用外鍵約束,而 pandas 似乎沒有自動執行此操作的選項。 在將連接傳遞給 pandas 的to_sql命令之前,必須為連接執行命令 'PRAGMA foreign_keys = ON':

cursor = connection.cursor()    
cursor.execute(create_data_table_query )
cursor.execute('PRAGMA foreign_keys = ON')
data.to_sql('data', connection, index_label='id', if_exists='append')

sqlite4 將默認啟用此功能。

另見

SQLite3 不支持外鍵約束嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM