设置关系选项卡

2024-09-29 21:51:18 发布

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

我想添加一个关系数据而不处理id。让我解释一下。例如,Nokta1和{}与Cihaz1相关。Nokta3与{}有关。所以这是一对多的关系。在

在将Cihaz1Cihaz2行添加到cihaz表之后,如何使用这些关系将Nokta1Nokta2和{}行插入到nokta表中?在

我的代码有错误吗?在

import sqlite3

# data
NOKTALAR = (
    ('Nokta1', 'AO', 'CVXY', '1'),
    ('Nokta2', 'AO', 'CVXY', '1'),
    ('Nokta3', 'BO', 'MESR', '1'),
    ('Nokta4', 'BO', 'MESR', '1'),
    ('Nokta5', 'BI', 'APTU', '2'),
    ('Nokta6', 'AI', 'FTRE', '1'),
    ('Nokta7', 'AI', 'FTRE', '1'),
)
CIHAZLAR = (
    ('Cihaz1'),
    ('Cihaz2'),
    ('Cihaz3'),
    ('Cihaz4'),
    ('Cihaz5'),
    ('Cihaz6'),
)

# get connection and cursor objects
conn = sqlite3.connect('iodatabase')
c = conn.cursor()

# create tables
c.execute('''create table cihaz (
    id integer primary key autoincrement,
    name text
)''')

c.execute('''create table nokta (
    id integer primary key autoincrement,
    name text,
    module text,
    type text,
    desc text,
    cihaz_id integer
    FOREIGN KEY(cihaz_id) REFERENCES cihaz(id)
)''')
c.execute('''create table link (
    nokta_id integer,
    cihaz_id integer,
)''')

Tags: textidexecute关系createtableintegersqlite3
1条回答
网友
1楼 · 发布于 2024-09-29 21:51:18

如果您想通过名称而不是id来关联它们,那么只需对名称使用一个外键。在

c.execute('''create table nokta
             id integer primary key autoincrement,
             name text,
             parent text
             FOREIGNKEY(parent) REFERENCES cihaz(name)''')

现在,当您插入一个nokta时,只需使用适当的父对象。在

^{pr2}$

现在要查询与特定cihaz相关的所有nokta,只需使用名称。在

 c.execute('select * from nokta where parent = ?', ('Cihaz1',))

相关问题 更多 >

    热门问题