flpms
flpms

Reputation: 254

MySQL in NodeJS is not working for multiple statements in INSERT INTO

I have de follow code.

let addressQuery = 'INSERT INTO addresses(postalCode, street, city, state) VALUES(?, ?, ?, ?);';
let addressValue = [client.postalCode.replace(/\-/gi, ''), client.address, client.city, client.state];

let clientQuery = `INSERT INTO client(name, email, password, postalCode, addressNumber, cellPhone) VALUES(?, ?, ?, ?, ?, ?);`;

let clientValues = [client.name, client.email, client.password, client.postalCode.replace(/\-/gi, ''), client.number, client.cellPhone ];

let addressSQL = mysql.format(addressQuery, addressValue);
let clientSQL = mysql.format(clientQuery, clientValues);

connection.query(`${addressSQL} ${clientSQL}`, (err, result) => {});

Which generate my query in addressSQL

INSERT INTO addresses(postalCode, street, city, state) VALUES('04545041', 'Rua Santa Justina', 'São Paulo', 'SP');`

and for clientSQL

INSERT INTO client(name, email, password, postalCode, addressNumber, cellPhone) VALUES('Keila', '[email protected]', 'Senha123Forte', '04545041', 352, 1130454006);

When I run queries manually the data is inserted in tables, but when I using mysql module in node only client data is inserted and nothing is inserted in addresses table. There's no error message from module only data not inserted. Both tables has a relationship in postalCode field. Anyone has a clue why data isn't inserted in addresses table?

Upvotes: 0

Views: 344

Answers (2)

Kai
Kai

Reputation: 228

Please read the node-mysql documentation

section connection option

multipleStatements: Allow multiple mysql statements per query. Be careful with this, it could increase the scope of SQL injection attacks. (Default: false)

Upvotes: 0

Jose Hermosilla Rodrigo
Jose Hermosilla Rodrigo

Reputation: 3683

You probably have to execute each query separately. So try this :

connection.query(`${addressSQL}`, (err, result) => {
   connection.query(`${clientSQL}`, (err, result_) => {
     // If no errors, two statements executed
   });
});

Upvotes: 1

Related Questions