INSERT不会马上触发

时间:2014-06-01 20:59:25

标签: mysql node.js node-mysql

我的所作所为:

  1. 从数据库中选择,
  2. 如果行不存在
  3. INSERT行
  4. 重复步骤1,从第3步中选择行
  5. 预期结果:经过4个步骤后,无论如何都会产生结果

    结果:select中没有行,但该行存在(请参阅phpMyAdmin)

    mysqlPool.getConnection(function(err, connection) {
            connection.query('SELECT * FROM x WHERE key = ? LIMIT 1', [ data.key ], function(err, result) {
                if (result.length == 0) {
                    // this works, I verified through phpMyAdmin:
                    connection.query('INSERT INTO x SET ?', { key: data.key });
                }
            });
    
            connection.query('SELECT * FROM x WHERE key = ? LIMIT 1', [ data.key ], function(err, result) {
                if (result.length != 0) {
                    // Expecting to be here, but result[0] is undefined?!
                } else {
                    // I END UP HERE? wtf
                } 
            });
            connection.release();
        });
    

    node-mysql是否需要commit;或类似的东西?

    我做错了什么?

1 个答案:

答案 0 :(得分:2)

我认为这是由于Node的异步性质,你需要在插入后调用回调中的第二个选择。类似于以下内容

mysqlPool.getConnection(function(err, connection) {
    connection.query('SELECT * FROM x WHERE key = ? LIMIT 1', [ data.key ], function(err, result) {
        if (result.length == 0) {
            // this works, I verified through phpMyAdmin:
            connection.query('INSERT INTO x SET ?', { key: data.key }, function(err, result){
                secondSelect();
            });
        }
        else
            secondSelect();
    });
});