Hossam Aldeen Ahmed
Hossam Aldeen Ahmed

Reputation: 782

Transactions in nodejs

i have 2 queries i want to execute inside a transaction rollback

var mysql = require('mysql');
var connection = mysql.createConnection({
    host: "host",
    user: "user",
    password: "pass"
});
var query1 = "insert into table1 values (1,2,3)";
var query2 = "update last_update set date=now()";
connection.beginTransaction(function(err) {
        if (err) {
            throw err;
        } 
        connection.query(query1, function(err, result) {
                if (err) {
                    connection.rollback(function() {
                        throw err;
                    });
                }
                });
        connection.query(query2, function(err, result) {
                if (err) {
                    connection.rollback(function() {
                        throw err;
                    });
                }
                });           
  });

when i run this nothing happened no errors and the queries don't excecute

Upvotes: 3

Views: 6891

Answers (1)

David Losert
David Losert

Reputation: 4802

If you begin a transaction, you will also have to commit it - else, nothing will get updated. You need to execute the following, but AFTER both queries ran:

connection.commit(function(err) {
    if (err) { 
      connection.rollback(function() {
        throw err;
      });
    }
    console.log('success!');
  });

To know when its AFTER both queries, you could either put the second query in the callback of the first, and the commit-query in the callback of the second - the problem is, that by this you enter the so called callback-Hell which makes your Code bascially unreadable.

How to avoid callback hell goes beyond the scope of this answer, but just have a look here to read more about it

Upvotes: 4

Related Questions