Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL syntax error using NPM 'mysql' module

Tags:

mysql

I'm using Node.js and the mysql NPM package to interact with a MySQL 5.7.14 instance. I'm getting an error about a syntax error in a query I'm making:

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 'INSERT INTO votes (user_uid, node_uid, sentiment) VALUES ('fakeid-123'' at line 1

At first I thought this must be a mistake I made in MySQL-escaping my input values, which I'm doing with the following in Node.js:

query =
  'START TRANSACTION; ' +
  'INSERT INTO votes (user_uid, node_uid, sentiment) VALUES (' +
    connection.escape(user_uid) + ', ' +
    connection.escape(node_uid) + ', ' +
    connection.escape(newValue) +
  '); ' +
  'UPDATE nodes SET votification=votification+' + newValue + ' ' +
  'WHERE uid=' + connection.escape(node_uid) + ';' +
  'COMMIT;'
connection.query(query, function(err, rows) { //.. blah blah

However, I added a console log to check the value of the query variable immediately before it is passed to connection.query, and I'm getting a perfectly legal-looking set of queries:

START TRANSACTION; INSERT INTO votes (user_uid, node_uid, sentiment) VALUES ('fakeid-123', 'start', 1); UPDATE nodes SET votification=votification+1 WHERE uid='start';COMMIT;

However, it's giving the above error. I tried copy-pasting this query string verbatim into a MySQL console session, and it performed admirably.

Is this an error in the NPM/mysql module? Does it not support transactions in this way, somehow? What else could be wrong? I assume the queries and transaction formation are okay, since they work when copy/pasted into MySQL directly.

For what it's worth, I'm using this module extensively and this is coincidentally the only query where I get such a failure, and the only place I'm using a transaction. I'm using a transaction here because I don't want to make these two calls "separately." I know the connection object is solid because I'm using it elsewhere in this scope with no problems.

Note/edit: I do see the documentation for the mysql NPM module on transactions (and I'm implementing this now instead), this is a much clunkier way to implement what I want and I'd like to understand why passing what I'm passing is failing.

like image 707
Steverino Avatar asked Jan 24 '26 05:01

Steverino


1 Answers

Playing around I came up with this while checking gave documentation:

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

Multiple queries are disabled by default.

like image 80
chris g Avatar answered Jan 26 '26 21:01

chris g



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!