Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs How to execute a mysql query with 2 statements

Tags:

sql

node.js

mysql

I'd like to execute 2 mysql statements with one query in node js. However this fails with the error:

ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

My node command and mysql query looks as follows.

connection.query( "UPDATE `table1` SET `count` = `count` + 1 WHERE `id` = ? LIMIT 1; INSERT INTO `table2` (`id`, `field1`, `datetime`, `field2`, `field3`, `field4`) VALUES     (NULL, ?, NOW(), ?, ?, 'impression');", 
    [var1, var2, var3,var4],
    function(err, rows) {
        connection.release();
        if (err != null) {
            // Do error logging
            console.log(this.sql);
            console.log(err);
        }
    });

Taking the mysql query statement from the console log and executing it manually works perfectly fine. Thus the problem must be caused by node mysql.

How can I execute these two statements with one query in node js?

Thx, i really appreciate your expertise!

like image 892
Manuel Avatar asked Mar 19 '26 04:03

Manuel


1 Answers

In node-mysql, support for multiple queries is disabled by default. To enable it, do it when creating your connection:

var connection = mysql.createConnection({multipleStatements: true});

Take a look at the docs for more information.

like image 79
Rodrigo Medeiros Avatar answered Mar 20 '26 20:03

Rodrigo Medeiros



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!