nodejs mysql无法执行查询

时间:2016-09-04 02:38:48

标签: javascript mysql node.js promise bluebird

我正在使用此套餐:https://github.com/mysqljs/mysql

this_obj.pool.getConnection似乎根本无法执行,因为我把console.log放在了。

MyLib.prototype.device_table_get_username = function(this_obj, user_id) {
  return new Promise(function (resolve, reject) {
    var sql = "select username from laravel_device where id = " + "'" + user_id + "'";

    console.log();
    console.log("---------");
    console.log(sql);

    // NOTE: ----------- it seems not running at all here. -----------------
    this_obj.pool.getConnection(function(err, connection) {
      console.log("1. no output here");

      connection.query(sql, function(err, rows, fields) {
        console.log("2. no output here");

        connection.release();

        if (err) throw err;

        var msg_obj = {
          rows: rows
        };

        resolve(msg_obj);
      });
    });
  });
}

完整代码

var config = require("../config.js");
var Promise = require('bluebird');
var mysql = require("mysql");
var ON_DEATH = require('death');


// Constructor
function MyLib() {
  // var
  this.db_username = config.db_username;
  this.db_password = config.db_password;
  this.db_name = config.db_name;
  this.db_host = config.db_host;

  this.pool = null;
}


MyLib.prototype.connect_mysql = function() {
    this.pool = mysql.createPool({
        connectionLimit: 400,
        host: this.db_host,
    user: this.db_username,
    password: this.db_password,
    database: this.db_name  
    }); 
}


// close mysql
MyLib.prototype.close_mysql = function() {
    this.pool.end(function (err) {
    // all connections in the pool have ended
    }); 
}


MyLib.prototype.clean_up = function() {
    var this_obj = this;
    ON_DEATH(function(signal, err) {
        console.log();
    console.log("---- script interupted ----");

    console.log("close mysql");
    this_obj.close_mysql();
    });
}


MyLib.prototype.run = function() {
  var this_obj = this;
  this.mqtt_acl_get_rows().then(function(msg_obj){
    var rows = msg_obj.rows;

    // http://stackoverflow.com/questions/28736452/bluebird-promise-serial-iteration-and-resolve-to-modified-array
    this_obj.map_series(this_obj, rows, this_obj.process_mqtt_acl_row).then(function(){

      // finish
      process.exit();
    });


  });

}


MyLib.prototype.device_table_get_username = function(this_obj, user_id) {
  return new Promise(function (resolve, reject) {
    var sql = "select username from laravel_device where id = " + "'" + user_id + "'";

    console.log();
    console.log("---------");
    console.log(sql);

    // NOTE: ----------- it seems not running at all here. -----------------
    this_obj.pool.getConnection(function(err, connection) {
      console.log("1. no output here");

      connection.query(sql, function(err, rows, fields) {
        console.log("2. no output here");

        connection.release();

        if (err) throw err;

        var msg_obj = {
          rows: rows
        };

        resolve(msg_obj);
      });
    });
  });
}



MyLib.prototype.user_table_get_username = function(user_id) {
    var this_obj = this;

  return new Promise(function (resolve, reject) {
    var sql = "select username from laravel_users where id = " + "'" + user_id + "'";

    console.log();
    console.log("---------");
    console.log(sql);

    // NOTE: ----------- it seems not running at all here. -----------------
    this_obj.pool.getConnection(function(err, connection) {
      connection.query(sql, function(err, rows, fields) {
        connection.release();

        if (err) throw err;

        var msg_obj = {
          rows: rows
        };
        resolve(msg_obj);
      });
    });
  });
}


MyLib.prototype.process_mqtt_acl_row = function(this_obj, value, index, length) {
    var row_id = value.id;
  var user_id = value.user_id;
  var mqtt_user_type_id = value.mqtt_user_type_id;
  var is_device = 2;
  var is_human = 1;

  if(mqtt_user_type_id == is_device) {
    console.log("-device-");
        this_obj.device_table_get_username(this_obj, user_id).then(function(msg_obj){      
            var rows = msg_obj.rows;
      console.log(msg_obj);
        });
  }
  else if(mqtt_user_type_id == is_human) {
    console.log("-human-");
        this_obj.user_table_get_username(user_id).then(function(msg_obj){
            var rows = msg_obj.rows;
      console.log(msg_obj);
        });
  }
  else {
    console.log("process_mqtt_acl_row, not calling");
  }

  return value;
}


// http://stackoverflow.com/questions/28736452/bluebird-promise-serial-iteration-and-resolve-to-modified-array
MyLib.prototype.map_series = function(this_obj, things, fn) {
  var results = [];

  return Promise.each(things, function(value, index, length) {
    // value
    // value == { id: 303, user_id: 4, mqtt_user_type_id: 1 }

    // call fn
    var ret = fn(this_obj, value, index, length);

    // push result
    results.push(ret);
    return ret;
  });
}


MyLib.prototype.mqtt_acl_get_rows = function() {
    var this_obj = this;

    return new Promise(function (resolve, reject) {
        var sql = "select id, user_id, mqtt_user_type_id from laravel_mqtt_acl order by id asc";

    console.log();
    console.log("---------");
    console.log(sql);

    // NOTE: this one is working
        this_obj.pool.getConnection(function(err, connection) {
      connection.query(sql, function(err, rows, fields) {
        connection.release();

        if (err) throw err;

        var msg_obj = {
          rows: rows
        };
        resolve(msg_obj); 
      });
    });
    });

}



module.exports = MyLib;

更新1 我将其从connectionLimit: 400更改为connectionLimit: 4。它似乎能够连接。我会做更多的测试。

1 个答案:

答案 0 :(得分:0)

尝试使用此代码处理MySQL数据库 首先在config / db中编写数据库代码,如

var config = require('./config');

var mysql = require(' mysql'); //对于mysql Connection

//CONFIGURATION FOR CREATING POOL
var pool =   mysql.createPool({
  connectionLimit:config.connectionLimit,
  host: config.host,
  user: config.user,
  password: config.password,
  database: config.database
});

module.exports = pool;

//在您要使用它的其他文件中。

var pool = require('../config/db');

pool.getConnection(function (err, connection) {
    if (!err)
    {
        email = req.user.email
        connection.query('delete from notification where user_id=(select id from users where email=?)', [email],
            function (err, noti_data){
                if (!err)
                {
                    deleted_device = noti_data.affectedRows
                    console.log('User Logout Successfully...');
                    res.json({'code': 200, 'status': 'Success', 'message': 'User Logout Successfully...'});
                    logger.info('URL=', URL.url, 'Responce=', 'User Logout Successfully...', 'Email id=', email);
                    return;
                }
                else
                {
                    console.log('Error for deleting and selecing details..', err);
                    res.json({'code': 200,'status': 'Error','message': 'Error for deleting and selecing details..'});
                    logger.error('URL=',URL.url, 'Responce=','Error for deleting and selecing details..','Email id=', email);
                    return;
                }
            });
            connection.release();
    }
    else
    {
        Errors.Connection_Error(res);
    }
});