1

This is my code.

pool.getConnection(function (err, connection) {
        connection.query("delete from userFiles where type = 1 and 
                          typeId = " + taskId + " and fileName 
                          NOT IN ('?') ",[oldFileNames], function (err, rows) {

        });
    });

Now the problem is , node js is generating query like this,

delete from table_name where type = 1 and typeId = 1 and 
fileName NOT IN (\'\'upload_149f2b78e5fd4096781bb5b8719b874f.png,upload_e8185e896cb0f8bb0b66d807cc60922c.png\'\')

I even tried like this,

connection.query("delete from userFiles where type = 1 and typeId = " + taskId + " and
                    fileName NOT IN ('" + oldFileNames + "') ", 
                      function (err, rows) {

This generated query like this,

delete from userFiles where type = 1 and typeId = 1 and 
fileName NOT IN (\'upload_149f2b78e5fd4096781bb5b8719b874f.png,
upload_e8185e896cb0f8bb0b66d807cc60922c.png\')

Both are causing mysql syntax error for the query(slashes are getting appended).

Can you suggest, what i can do to get rid of this error.

3
  • What's oldFileNames ? An array or a string ? Commented Nov 6, 2015 at 8:45
  • @DenysSéguret its a comma separated value from form. Commented Nov 6, 2015 at 8:46
  • OK, It should be an array. See updated answer. Commented Nov 6, 2015 at 8:48

2 Answers 2

3

You're not supposed to add the quotes yourself around the ? placeholder. Remove them.

You should also pass an array, not a string. Assuming it's a clean string, you can just use split.

connection.query(
      "delete from userFiles where type = 1 and typeId = " + taskId +
      " and fileName NOT IN (?) ", [oldFileNames.split(/,\s*/)],
      function (err, rows) {
Sign up to request clarification or add additional context in comments.

6 Comments

I got like this, delete from userFiles where type = 1 and typeId = 1 and fileName NOT IN (\'upload_d46d172a7aaabf50f7598a334cc2ce37.png,upload_b008eaa4f8731bfab7d3aec3614cf15e.png\')
@NiranjanNRaju It looks like your oldFileNames string contains quotes, and that's a problem. Can you look at that ?
Nope... im passing only comma separated names.
And above query is deleting all rows.
What's oldFileNames ? An array or a string ? An array is needed, not a string.
|
1

A possible solution is to use connection.escape();

connection.query("delete from userFiles where type = 1 and typeId = " + taskId + " 
and fileName NOT IN (" + connection.escape(oldFileNames) + ")");

2 Comments

none of the rows r getting deleted even if there r some rows.
this only works when oldFileNames is an array of strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.