Node-mysql2: Multiple query with escaped data

Created on 16 Sep 2019  路  4Comments  路  Source: sidorares/node-mysql2

How can I use multiple queries and escape data? Now I'm using queries like a
db.query('INSERT INTO users (name, lastname) VALUES (?, ?)', [username, lastname])
But that will insert one row. How I can insert many rows by one query?

question

All 4 comments

first, you don't need multiple statements to insert multiple rows, see https://stackoverflow.com/questions/6889065/inserting-multiple-rows-in-mysql answer

afaik the only special thing to do to use multiple statements is to set {multipleStatements: true} flag in connection config. ? placeholders are used same way

What have you tried and what problems do you have @HulioEglesias ?

I have object

user: {
  characters: [{name: 'Char1', level: 12}, {name: 'char2', level: 54}];
}

Count of characters is different. I need insert all array of objects to table 'characters'
What a string I should have? @sidorares

try this: db.query('INSERT INTO users (name, lastname) VALUES ?', [['Char1', 12], ['Char2', 54]])

see https://github.com/mysqljs/mysql#escaping-query-values:

Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')

Note that this is client-side escape ( e.i it'll build query like INSERT INTO users (name, lastname) VALUES ('Char1', 12), ('Char2', 54) on the client before sending it to server

If you want to use prepared statements ( aka .execute()) you must use same number of placeholders as number of parameters you pass

try this: db.query('INSERT INTO users (name, lastname) VALUES ?', [['Char1', 12], ['Char2', 54]])

see https://github.com/mysqljs/mysql#escaping-query-values:

Nested arrays are turned into grouped lists (for bulk inserts), e.g. [['a', 'b'], ['c', 'd']] turns into ('a', 'b'), ('c', 'd')

Note that this is client-side escape ( e.i it'll build query like INSERT INTO users (name, lastname) VALUES ('Char1', 12), ('Char2', 54) on the client before sending it to server

If you want to use prepared statements ( aka .execute()) you must use same number of placeholders as number of parameters you pass

It works... but the array has to be included in another array... I don't know if I am clear :
[
['Char1', 12],
['Char2', 54],
]
won't work.
But :
[ <---- 'extra' array dimension ?
[
['Char1', 12],
['Char2', 54],
]
]
will work...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

MHDante picture MHDante  路  4Comments

HugoMuller picture HugoMuller  路  3Comments

SiroDiaz picture SiroDiaz  路  6Comments

sidorares picture sidorares  路  7Comments

picbenoit picture picbenoit  路  6Comments