简体   繁体   English

sqlite3外键根本不起作用

[英]sqlite3 foreign key not working at all

    cur.execute("CREATE TABLE users(id integer PRIMARY KEY, username TEXT, password TEXT, email TEXT)")
    cur.execute("CREATE TABLE posts(id integer PRIMARY KEY, body TEXT, user_id int, FOREIGN KEY(user_id) REFERENCES users(id))")

I already enabled pragma foreign_keys = on, and it returned a 1. I created this database with python, and I used a database viewing program to check the fields. 我已经启用了pragma foreign_keys = on,它返回了1。我用python创建了这个数据库,并且我使用了数据库查看程序来检查字段。 It showed everything correct from the primary keys, to the text fields, BUT no foreign key. 它显示了从主键到文本字段的所有正确内容,但没有外键。 It displays user_id as an int, nothing more. 它将user_id显示为int,仅此而已。 I also don't get any values put into it when making inserts. 进行插入时,我也没有输入任何值。 I feel that if I insert a user, than it should create a row, and be references in posts. 我觉得,如果我插入一个用户,那么它应该创建一行并在帖子中引用。 But when I query the user_id field, it returns 'none'. 但是,当我查询user_id字段时,它返回“ none”。 What am I doing wrong? 我究竟做错了什么?

edit:here is how I got it to work 编辑:这是我如何使其工作

@app.route('/add', methods=['POST'])
def add():       
    c = g.db.execute("INSERT INTO posts(body) VALUES(?)", [request.form['body']])
    b = g.db.execute("INSERT INTO users(username) VALUES(?)", [request.form['name']])
    get = g.db.execute("SELECT id from users where username=?", [request.form['name']])
    id = get.fetchone()  
    userid=str(id[0])
    bet = g.db.execute("SELECT id from posts where body=?", [request.form['body']])
    bid = bet.fetchone()
    postid = str(bid[0])
    e = g.db.execute("UPDATE posts SET user_id = (?) where id = (?)  ", [userid,postid])
    g.db.commit()
    flash('subbmited')
    return redirect(url_for('home'))

Foreign keys are used for managing relationships between records. 外键用于管理记录之间的关系。 However, in your code, you have not told the database that the two inserted records are related in any way. 但是,在您的代码中,您没有告诉数据库两个插入的记录有任何关联。

You should insert the users record first so that you can use the newly inserted ID for the posts record: 您应该首先插入users记录,以便可以将新插入的ID用于posts记录:

def add():
    cursor = g.db.cursor()
    cursor.execute("INSERT INTO users(username) VALUES(?)", [request.form['name']])
    g.db.execute("INSERT INTO posts(body, user_id) VALUES(?,?)",
                 [request.form['body'], cursor.lastrowid])
    g.db.commit()
    ...

(Do you really want to create a new user for each post?) (您是否真的要为每个帖子创建一个新用户?)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM