Search code examples
javascriptmysqlsqlnode.jsnode-mysql

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', 'keila@dressandgo.com.br', '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?


Solution

  • 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
       });
    });