How to write long MySQL queries in node JS

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to write long MySQL queries in node JS



How to write long MySQL queries on many lines instead of one very long line for easy reading and modifying.
I only know this way to write them:


app.get('/example', function(req, res){
x = 'SELECT doctors_schedule.*, employees.employee_name, doctors.degree FROM doctors_schedule JOIN employees ON employees.employee_id = doctors_schedule.doctor_id JOIN doctors ON doctors.doctor_id = employees.employee_id ORDER BY employees.employee_id';
connection.query(x, function(error, rows, fields){
if(error){console.log(error);}
res.json(rows);
});
});




2 Answers
2



Use template literals (template strings):


app.get('/example', function(req, res){
const x = `SELECT doctors_schedule.*, employees.employee_name, doctors.degree
FROM doctors_schedule
JOIN employees ON employees.employee_id = doctors_schedule.doctor_id
JOIN doctors ON doctors.doctor_id = employees.employee_id
ORDER BY employees.employee_id`;

connection.query(x, function(error, rows, fields){
if(error){
console.log(error);
}
res.json(rows);
});
});



This feature is available since Node.js v.4.0.0.





Thank you so much, I can not imagine that it is that simple
– A.Kallas
yesterday



es6 brought us template literals. You can use backticks, and span multiple lines easily. Read more about this here:


app.get('/example', function(req, res){
x = `
SELECT doctors_schedule.*, employees.employee_name, doctors.degree
FROM doctors_schedule
JOIN employees ON employees.employee_id = doctors_schedule.doctor_id
JOIN doctors ON doctors.doctor_id = employees.employee_id
ORDER BY employees.employee_id
`;
connection.query(x, function(error, rows, fields){
if(error){console.log(error);}
res.json(rows);
});
});






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Keycloak server returning user_not_found error when user is already imported with LDAP

PHP parse/syntax errors; and how to solve them?

How to scale/resize CVPixelBufferRef in objective C, iOS