Node.js + MySQL - handling transactions

前端 未结 5 1383
慢半拍i
慢半拍i 2021-02-07 22:27

I am building an app on node.js using express, and node-mysql driver. There is a couple of cases in my app when I need to make a series of database inserts/updates. I want them

5条回答
  •  春和景丽
    2021-02-07 22:59

    Depending on how complex your transaction is you might run into some ugly nesting trying to queue your queries from Node, which might introduce ugly variable scoping issues.

    What you can do instead is write a stored procedure and end it by SELECTing a success/failure flag, then query the procedure with node-mysql as you would a SELECT query. Here's how the stored procedure might look:

    DELIMITER //
    DROP PROCEDURE IF EXISTS MyProcedure //
    CREATE PROCEDURE MyProcedure(IN param1 VARCHAR/*, My, Parameters, ... */)
    BEGIN
    
        DECLARE EXIT HANDLER FOR NOT FOUND, SQLWARNING, SQLEXCEPTION
        BEGIN
            ROLLBACK;
            SELECT 0 AS res;
        END;
    
        START TRANSACTION;
        # My Transaction ...
    
    
        COMMIT;
        SELECT 1 AS res;
    
    END //
    DELIMITER ;
    

    Your Node code would look something like this:

    var mysql = require('mysql');
    
    var client = mysql.createClient({
        host    : '127.0.0.1',
        user    : 'username',
        password: 'password'
    });
    client.query('USE mydatabase');
    
    var myParams = "'param1', 'param2', ... ";
    client.query("CALL MyProcedure(" + myParams + ")", function(err, results, fields) {
        if (err || results[0].res === 0) {
            throw new Error("My Error ... ");
        } else {
            // My Callback Stuff ...
    
        }
    });
    

提交回复
热议问题