最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node.js mysql error cannot read property of undefined? - Stack Overflow

programmeradmin0浏览0评论

I have a program that inserts SMDR data into a database as it es in.

Here is my code:

var net = require('net'),
    mysql = require('mysql'),
    PORT = 1752,
    HOST = '192.168.10.2',
    pool = mysql.createPool({
        host: 'localhost',
        port: 3307,
        user: 'root',
        password: 'root',
        database: 'mydb'
    });

function connectionListener(conn) {
    console.log('Listening for ining calls...');
}

function logCall(phonenumber, operator) {
    pool.getConnection(function(err, connection) {
        if (!err) { // If no error exists 
            var opquery = connection.query('SELECT OperatorID FROM tblOperators WHERE Phone_Login = ' + operator, function(err, rows) {
                if (err) {
                    console.error(err);
                    connection.release();
                    return;
                }
                var query = connection.query('INSERT INTO ining_calls(phone_number, OperatorID) VALUES("' + 
                phonenumber + '", "' + rows[0].OperatorID + '") ON DUPLICATE KEY UPDATE OperatorID=OperatorID, date_created=NOW()', function(err, rows) {
                    if (err) {
                        console.error(err);
                    }
                    connection.release();
                });
            });
        } else {
            console.error(err);
        }
    });
}

function processdata(data) {
    var phonedata = data.toString().match(/([0-9]?)([0-9]{10})/),
        operdata = data.toString().match(/([*])([0-9]{4})/);
    if (phonedata !== null && operdata !== null) {
        var phonenumber = phonedata[2], 
            oper = operdata[2];

        oper = oper.replace('*', '');
        phonenumber = phonenumber.slice(0,3)+"-"+phonenumber.slice(3,6)+"-"+phonenumber.slice(6);
        logCall(phonenumber, oper);
    }
}
logCall('999-999-9999', '1203');
var conn = net.createConnection(PORT, HOST, connectionListener);
conn.on('data', processdata);
conn.setEncoding('utf8');

And here is the error that I get, when OperatorID clearly does exist within the table:

c:\xampp\htdocs>node listener
Listening for ining calls...

c:\xampp\htdocs\node_modules\mysql\lib\protocol\Parser.js:82
        throw err;
          ^
TypeError: Cannot read property 'OperatorID' of undefined
    at Query._callback (c:\xampp\htdocs\listener.js:27:48)
    at Query.Sequence.end     (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Sequence.js:96:24)
    at Query._handleFinalResultPacket     (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Query.js:143:8)
    at Query.EofPacket (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Query.js:127:8)
    at Protocol._parsePacket (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Protocol.js:271:23)
    at Parser.write (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Parser.js:77:12)
    at Protocol.write (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Protocol.js:39:16)
    at Socket.<anonymous> (c:\xampp\htdocs\node_modules\mysql\lib\Connection.js:82:28)
    at Socket.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:764:14)

Does anyone have any ideas as to why this would happen, I have a production database that uses this, has the same exact information and it works?

I have a program that inserts SMDR data into a database as it es in.

Here is my code:

var net = require('net'),
    mysql = require('mysql'),
    PORT = 1752,
    HOST = '192.168.10.2',
    pool = mysql.createPool({
        host: 'localhost',
        port: 3307,
        user: 'root',
        password: 'root',
        database: 'mydb'
    });

function connectionListener(conn) {
    console.log('Listening for ining calls...');
}

function logCall(phonenumber, operator) {
    pool.getConnection(function(err, connection) {
        if (!err) { // If no error exists 
            var opquery = connection.query('SELECT OperatorID FROM tblOperators WHERE Phone_Login = ' + operator, function(err, rows) {
                if (err) {
                    console.error(err);
                    connection.release();
                    return;
                }
                var query = connection.query('INSERT INTO ining_calls(phone_number, OperatorID) VALUES("' + 
                phonenumber + '", "' + rows[0].OperatorID + '") ON DUPLICATE KEY UPDATE OperatorID=OperatorID, date_created=NOW()', function(err, rows) {
                    if (err) {
                        console.error(err);
                    }
                    connection.release();
                });
            });
        } else {
            console.error(err);
        }
    });
}

function processdata(data) {
    var phonedata = data.toString().match(/([0-9]?)([0-9]{10})/),
        operdata = data.toString().match(/([*])([0-9]{4})/);
    if (phonedata !== null && operdata !== null) {
        var phonenumber = phonedata[2], 
            oper = operdata[2];

        oper = oper.replace('*', '');
        phonenumber = phonenumber.slice(0,3)+"-"+phonenumber.slice(3,6)+"-"+phonenumber.slice(6);
        logCall(phonenumber, oper);
    }
}
logCall('999-999-9999', '1203');
var conn = net.createConnection(PORT, HOST, connectionListener);
conn.on('data', processdata);
conn.setEncoding('utf8');

And here is the error that I get, when OperatorID clearly does exist within the table:

c:\xampp\htdocs>node listener
Listening for ining calls...

c:\xampp\htdocs\node_modules\mysql\lib\protocol\Parser.js:82
        throw err;
          ^
TypeError: Cannot read property 'OperatorID' of undefined
    at Query._callback (c:\xampp\htdocs\listener.js:27:48)
    at Query.Sequence.end     (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Sequence.js:96:24)
    at Query._handleFinalResultPacket     (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Query.js:143:8)
    at Query.EofPacket (c:\xampp\htdocs\node_modules\mysql\lib\protocol\sequences\Query.js:127:8)
    at Protocol._parsePacket (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Protocol.js:271:23)
    at Parser.write (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Parser.js:77:12)
    at Protocol.write (c:\xampp\htdocs\node_modules\mysql\lib\protocol\Protocol.js:39:16)
    at Socket.<anonymous> (c:\xampp\htdocs\node_modules\mysql\lib\Connection.js:82:28)
    at Socket.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:764:14)

Does anyone have any ideas as to why this would happen, I have a production database that uses this, has the same exact information and it works?

Share asked Dec 22, 2014 at 21:58 JuanJuan 911 gold badge1 silver badge7 bronze badges 5
  • 2 looks like rows[0] is undefined. If you ever get an empty result set, you're going to run into this problem. A good practice here would be to capture the relevant row in its own variable, and check its existence before trying to access any of its potential values. You could also create a guard clause that just returns if rows.length < 1, preventing any further execution and avoiding this problem. – Jordan Foreman Commented Dec 22, 2014 at 22:05
  • On my production database, I can truncate the whole table 'ining_calls', and rerun this script, and it will run just fine, but when I try to run on my secondary database, it just doesn't work for some reason. – Juan Commented Dec 22, 2014 at 22:15
  • tblOperators is loaded with data on both databases, so OperatorID is defined, this cannot be the issue. – Juan Commented Dec 22, 2014 at 22:16
  • Never mind I figured out my own problem, thanks anyways! – Juan Commented Dec 22, 2014 at 22:31
  • 8 What was it? It might be worth adding your solution as an answer in case anyone else has this same issue – Jordan Foreman Commented Dec 23, 2014 at 3:29
Add a ment  | 

1 Answer 1

Reset to default 1

first check your query result is blank or not if it blank than you will get that error ex.

var opquery = connection.query('SELECT OperatorID FROM tblOperators WHERE Phone_Login = ' + operator, function(err, rows) {
            if (err) {
                console.error(err);
                connection.release();
                return;
            }
            else
            {
              if(rows!="")
              {
                  var query = connection.query('INSERT INTO ining_calls(phone_number, OperatorID) VALUES("' + 
            phonenumber + '", "' + rows[0].OperatorID + '") ON DUPLICATE KEY UPDATE OperatorID=OperatorID, date_created=NOW()', function(err, rows) {
                if (err) {
                    console.error(err);
                }
                connection.release();
            });
              }
              else
              {
                  console.log('can not get data from tabel');
              }
            }
发布评论

评论列表(0)

  1. 暂无评论