Advertisement
Guest User

Untitled

a guest
Feb 25th, 2020
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. const faker = require('faker');
  2. const mysql = require('mysql');
  3.  
  4. const connection = mysql.createConnection({
  5. host : 'localhost',
  6. user : 'root',
  7. database : 'db_books'
  8. });
  9.  
  10. const firstName = 'Bill';
  11. const lastName = 'Reinger';
  12.  
  13. connection.connect();
  14.  
  15.  
  16. function getQuery(sql, params){
  17. return new Promise((resolve, reject) => {
  18. connection.query(sql,params,function (error, results, fields){
  19. if (error) {
  20. reject(error);
  21. }
  22. resolve(results);
  23.  
  24. });
  25. });
  26. }
  27.  
  28. let sql = 'SELECT * FROM `authors` WHERE first_name=? and last_name=? limit 1;';
  29.  
  30. getQuery(sql,[firstName, lastName])
  31.  
  32. .then(authors=>{
  33. sql = 'SELECT * FROM `books_authors` WHERE author_id=?;';
  34. return getQuery(sql,[authors[0].id]);
  35. })
  36. .then(books_authors=>{
  37. sql = 'SELECT * FROM `books` WHERE id IN (?);';
  38. const args = books_authors.map(b_a => b_a.book_id);
  39. return getQuery(sql,[args]);
  40. })
  41. .then(books => {
  42. console.log(books);
  43. })
  44. .catch(error => {
  45. console.log(error);
  46. })
  47. .finally(()=>{
  48. connection.end();
  49. });
  50.  
  51.  
  52. // let sql = 'SELECT * FROM `authors` WHERE first_name=? and last_name=? limit 1;';
  53. // connection.query(sql,[firstName, lastName], function (error, results, fields) {
  54. // if (error) throw error;
  55. // let authorId = results[0].id;
  56. // sql = 'SELECT * FROM `books_authors` WHERE author_id=?;';
  57. // connection.query(sql,[authorId], function (error, books_authors, fields) {
  58. // console.log(books_authors);
  59. // sql = 'SELECT * FROM `books` WHERE id IN (?);';
  60. // const args = books_authors.map(b_a => b_a.book_id);
  61. // connection.query(sql,[args],function (error, books, fields) {
  62. // if (error) throw error;
  63. // console.log(books);
  64. // connection.end();
  65. // });
  66. // });
  67. //
  68. //
  69. // console.log(authorId);
  70. // });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement