简体   繁体   English

插入前检查外键是否完整

[英]Check if foreign keys is integrity before insert

I have two tables that follow and profile, and follow in the table insert id of the profile below (foreign keys) 我有两个表和个人资料,并在下面的个人资料表格插入ID(外键)中跟随

How can I be sure before inserting into my table foreign keys that match a profile id of the table? 在将与表的概要文件ID匹配的外键插入到表中之前,如何确定?

var o_segui = {
    seguace_id: profilo,
    seguito_id: data.profilo_da_seguire,
    created: new Date()
};

connection.query('INSERT INTO follow SET ?', o_segui, function(error, rows) {
 if (error) {
     var err = "Error on 'seguiAction': " + error;
     console.error(err);
     throw err;
 }

now i check that now exists with a query before insert like: 现在我检查现在是否存在查询,然后再插入:

connection.query('SELECT count(*) as n FROM profile WHERE id =' + connection.escape(profilo_da_seguire), function(error, rows) {
if (error) {
    var err = "Error on 'verifico Profilo': " + error;
    console.error(err);
    throw err;
}

console.log(rows);

if (rows.shift().n > 0) { then OK

UPDATE in my Insert i do throw err...if i comment throw err server node dosen't go down...i have to comment this line and close connection ? 在我的插入中更新我会抛出err ...如果我发表评论err server node not down ...我必须评论这一行并关闭连接吗?

Check-before-set is usually not a good approach while using database. 使用数据库时, 预先检查通常不是一个好方法。 Mostly because you will have to take into account possible concurrent access to your tables. 通常是因为您必须考虑对表的可能的并发访问。

Anyway, concerning foreign key constraints, if you use InnoDB, the engine will check for you at insert-time. 无论如何,关于外键约束,如果您使用InnoDB,引擎在插入时检查您。

So, I think it is better to be optimistic by trying to insert. 因此,我认为最好通过插入来保持乐观。 But be prepared to handle gracefully a possible failure. 但要准备好妥善处理可能的故障。

EDIT: I build an example in order to "prove" that integrity constraints are enforced by the DB engine InnoDB: http://sqlfiddle.com/#!2/f372d/1 编辑:我建立一个示例,以“证明”完整性约束由数据库引擎InnoDB强制执行: http ://sqlfiddle.com/#!2/ f372d/1

As you will see, faulty data are not inserted in the DB. 如您将看到的,错误的数据没有插入数据库。 In your program you will have to deal with the corresponding exception/error. 在您的程序中,您将必须处理相应的异常/错误。

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

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