正确使用FOREIGN KEY功能

时间:2018-06-14 08:21:20

标签: r sqlite foreign-keys rsqlite

在我的数据库中,我有两个名为艺术家和曲目的表。在创建轨道表时,我将FOREIGN KEY设置为artist。但是当我运行这个显示的代码时,插入一个跟不存在的艺术家的轨道行是没有问题的。

那绝对不是目标...

http://homepages.ecs.vuw.ac.nz/~adam/scie201/lec_R_SQLite.html上我发现我必须使用类似PRAGMA foreign_keys=ON的功能启用此功能 - 但我不知道应该如何对此进行编码......

这是我的问题:如何正确实施FOREIGN KEY功能?

非常感谢您的帮助!

现在我的代码:

   # needed packages for this script
   # install.packages("sqldf")  # install this package if necessary
   library(sqldf)

    # connection to the database TestDB.sqlite
    db=dbConnect(SQLite(), dbname="TestDB.sqlite")

    # create the first table of the database
    dbSendQuery(conn = db,
        "CREATE TABLE IF NOT EXISTS artists
        (ID INTEGER,
        name TEXT,
        PRIMARY KEY (ID))")

    # create the second table
    dbSendQuery(conn = db,
        "CREATE TABLE IF NOT EXISTS tracks
        (track_ID INTEGER,
        title TEXT,
        artist INTEGER,
        FOREIGN KEY(artist) REFERENCES artists(ID),
        PRIMARY KEY (track_ID))")

    # filling the artist table with two rows
    dbSendQuery(conn = db,
        paste0("INSERT INTO artists
        VALUES (1,'Tom Chapin')"))
    dbSendQuery(conn = db,
        paste0("INSERT INTO artists
        VALUES (2,'Harry Chapin')"))

    # filling the tracks table
    dbSendQuery(conn = db,
        paste0("INSERT INTO tracks
        VALUES (1,'Cats in the Cradle',1)"))
    # with the following tracks filling order there must occur an error
    ### but how to switch on the 'FOREIGN KEY'
    dbSendQuery(conn = db,
        paste0("INSERT INTO tracks
        VALUES (2,'Cats in the Cradle',3)"))

    # list the tables of the database
    print(dbListTables(db))

    # list the columns of a specific table
    print(dbListFields(db,"artists"))  # of artists
    print(dbListFields(db,"tracks"))   # of tracks

    # show the data ...
    print(dbReadTable(db,"artists"))  # of artists
    print(dbReadTable(db,"tracks"))   # of tracks

    # close the connection
    dbDisconnect(db)

1 个答案:

答案 0 :(得分:0)

打开连接后,您需要将PRAGMA语句发送到数据库:

dbExecute(conn = db, "PRAGMA foreign_keys=ON")

请注意,文档说明:

  

默认情况下禁用外键约束(为了向后兼容),因此必须为每个数据库连接单独启用。

每次连接数据库时都必须这样做。