Guest User

Untitled

a guest
May 4th, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.66 KB | None | 0 0
  1. let mysql = require('mysql');
  2. let dbconn = {
  3. host: "localhost", // make sure to replace with your own configuration
  4. user: "root", // make sure to replace with your own configuration
  5. password: "password", // make sure to replace with your own configuration
  6. connectionLimit: 100, // make sure to replace with your own configuration
  7. database: "db" // make sure to replace with your own configuration
  8. };
  9. let sql = mysql.createPool(dbconn);
  10. let jsonObj;
  11. /*
  12. * let's assume that the stored JSON has the following structure:
  13. *
  14. * "master_key" : {
  15. * sub_key1: "test1",
  16. * sub_key2: "test2",
  17. * sub_key3: {
  18. * sub_key4: "test4"
  19. * }
  20. *
  21. */
  22.  
  23. sql.getConnection((err, conn) => {
  24. if(err) throw err;
  25. // We can SELECT it
  26. conn.query("SELECT json_Column FROM test_Table",(error, row) => {
  27. conn.release();
  28. if(error) throw error;
  29. jsonObj = JSON.parse(row[0].json_Column); //you can now handle the json keys as usual
  30. // jsonObj.master_key || jsonObj.master_key.sub_key1 || jsonObj.master_key.sub_key3.sub_key4 || however you want
  31. });
  32.  
  33. // We can INSERT it
  34. jsonObj = {/*your JSON here*/};
  35. conn.query("INSERT INTO test_Table(json_Column) VALUES ?", [JSON.stringify(jsonObj)],(error, row) => {
  36. conn.release();
  37. if(error) throw error;
  38. console.log(row[0]);
  39. });
  40.  
  41. // We can UPDATE it
  42. jsonObj = {/*your JSON here*/};
  43. conn.query("UPDATE test_Table SET json_Column = ?", [JSON.stringify(jsonObj)],(error, row) => {
  44. conn.release();
  45. if(error) throw error;
  46. console.log(row[0]);
  47. });
  48. });
Add Comment
Please, Sign In to add comment