F_K列有问题,无法获取它的值

时间:2019-07-26 19:03:27

标签: python python-3.x sqlite user-interface tkinter

1 个答案:

答案 0 :(得分:1)

您似乎已启用了按以下条件强制执行的约束的例外:-

  

有一个例外:如果跟踪表中的外键列   为NULL,则在artist表中不需要相应的条目。

SQLite Foreign Key Support

.....

  

提示:如果应用程序需要在歌手和曲目之间建立更严格的关系,而trackartist列中不允许使用NULL值,则只需在架构中添加适当的“ NOT NULL”约束即可。

根据技巧,解决方案是使用

在客户表中定义 p_id
p_id INTEGER NOT NULL

如果未提供p_id,则NOT NULL约束冲突将阻止插入。

请考虑以下示例:-

/* Example as per issue/question */
DROP TABLE IF EXISTS client;
DROP TABLE IF EXISTS product;
CREATE TABLE IF NOT EXISTS product (p_id INTEGER PRIMARY KEY, product TEXT, price FLOAT);
CREATE TABLE IF NOT EXISTS client (c_id INTEGER PRIMARY KEY, client TEXT, phone INTEGER, p_id INTEGER REFERENCES product(p_id));
INSERT INTO product (product,price) VALUES ('product1', 76576.0),('product2',6546.0),('product3',1200.0);
INSERT INTO client (client,phone) VALUES ('Fred',1234567890); -- inserted but with null
INSERT INTO client (client,phone,p_id) VALUES ('Bert',2345678901,2); -- Works but with p_id being null
SELECT * FROM client;
  • 结果:-
  • enter image description here

然后用NOT NULL编码:-

/* Example as above BUT with client p_id column being defined with NOT NULL */ 
DROP TABLE IF EXISTS client;
DROP TABLE IF EXISTS product;
CREATE TABLE IF NOT EXISTS product (p_id INTEGER PRIMARY KEY, product TEXT, price FLOAT);
CREATE TABLE IF NOT EXISTS client (c_id INTEGER PRIMARY KEY, client TEXT, phone INTEGER, p_id INTEGER NOT NULL REFERENCES product(p_id));
INSERT INTO product (product,price) VALUES ('product1', 76576.0),('product2',6546.0),('product3',1200.0);
INSERT OR IGNORE INTO client (client,phone,p_id) VALUES ('Bert',2345678901,2); -- Works
INSERT OR IGNORE INTO client (client,phone) VALUES ('Fred',1234567890); -- not null constraint so not inserted (ignored for demo)
SELECT * FROM client;
  • 结果:-
  • enter image description here

  • 请注意,已经使用了INSERT或IGNORE,因为这将跳过NOT NULL约束冲突,并允许在演示中显示结果。