Advertisement
Guest User

Untitled

a guest
Sep 16th, 2017
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. var mysql = require('mysql');
  2. var db_connect = (function () {
  3. function db_connect() {
  4. mysqlConnConfig = {
  5. host: "localhost",
  6. user: "username",
  7. password: "password",
  8. database: "db_name"
  9. };
  10. }
  11. db_connect.prototype.unitOfWork = function (sql) {
  12. mysqlConn = mysql.createConnection(mysqlConnConfig);
  13. try {
  14. sql(mysqlConn);
  15. } catch (ex) {
  16.  
  17. console.error(ex);
  18. } finally {
  19. mysqlConn.end();
  20. }
  21. };
  22. return db_connect;
  23. })();
  24. exports.db_connect = db_connect;
  25.  
  26. var query1 = "SELECT * FROM table1";
  27. sql.query(query1,function(error,response){
  28. if(error){
  29. console.log(error);
  30. }
  31. else{
  32. console.log(response);
  33. }
  34. })
  35.  
  36. forever start app.js
  37.  
  38. "stack": ["Error: Connection lost: The server closed the connection.", " at Protocol.end (/path/to/my/file/node_modules/mysql/lib/protocol/Protocol.js:109:13)", " at Socket.<anonymous> (/path/to/my/file/node_modules/mysql/lib/Connection.js:102:28)", " at emitNone (events.js:72:20)", " at Socket.emit (events.js:166:7)", " at endReadableNT (_stream_readable.js:913:12)", " at nextTickCallbackWith2Args (node.js:442:9)", " at process._tickDomainCallback (node.js:397:17)"],
  39. "level": "error",
  40. "message": "uncaughtException: Connection lost: The server closed the connection.",
  41. "timestamp": "2017-09-13T21:22:25.271Z"
  42.  
  43. var db_config = {
  44. host: 'localhost',
  45. user: 'root',
  46. password: '',
  47. database: 'example'
  48. };
  49.  
  50. var connection;
  51.  
  52. function handleDisconnect() {
  53. connection = mysql.createConnection(db_config); // Recreate the connection, since
  54. // the old one cannot be reused.
  55.  
  56. connection.connect(function(err) { // The server is either down
  57. if(err) { // or restarting (takes a while sometimes).
  58. console.log('error when connecting to db:', err);
  59. setTimeout(handleDisconnect, 2000); // We introduce a delay before attempting to reconnect,
  60. } // to avoid a hot loop, and to allow our node script to
  61. }); // process asynchronous requests in the meantime.
  62. // If you're also serving http, display a 503 error.
  63. connection.on('error', function(err) {
  64. console.log('db error', err);
  65. if(err.code === 'PROTOCOL_CONNECTION_LOST') { // Connection to the MySQL server is usually
  66. handleDisconnect(); // lost due to either server restart, or a
  67. } else { // connnection idle timeout (the wait_timeout
  68. throw err; // server variable configures this)
  69. }
  70. });
  71. }
  72.  
  73. handleDisconnect();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement