Question

I am using node-mysql for the first time, and I have a program with no errors, no warnings, but is not working properly... Here is the code for the program, very simple:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database:  'nodetest',
  port: 8080
});

connection.connect();
var usr = "BLASHDASD"
var userId = usr;
var sql = 'UPDATE userlist SET user1= ' + connection.escape(userId) + ' WHERE id=1 ';
console.log(sql);

connection.query('sql', function(err, rows, fields) {
  console.log(err);
  console.log("BLAHSDBKASD");
});

connection.end();

And here is the console output:

C:\wamp\www\nodePHP-master\js>node nodeTest.js
UPDATE userlist SET user1= 'BLASHDASD' WHERE id=1

But nothing is happening in my MySQL table... I even copied and pasted the UPDATE line above and just ran it as SQL code and it worked great... Need some ideas of what is going on. Thanks a bunch

EDIT:

Answered my own question... was listening on wrong port, so connection was failing. Here is updated code for those interested/search in the future:

//TEST

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database:  'nodetest',
  port: 3306,
});

connection.connect(function(err){
    if(err) {
        console.log(err)
    } else {
        console.log("connected");
    }
});
var usr = "BLASHDASD"
var userId = usr;
var sql = 'UPDATE userlist SET user1= ' + connection.escape(userId) + ' WHERE id=1 ';
console.log(sql);

connection.query(sql, function(err, rows, fields) {
  console.log(err);
});

connection.end();
Was it helpful?

Solution

You are having problems with node's asynchronous nature, a very common issue when coming to Node. You also had a small but significant error in your code (you have 'sql' as a quoted string), but here is something structurally similar that should point you in the right direction.

var mysql      = require('mysql');
var connection = mysql.createConnection({
    host     : 'locahost',
    user     : 'foo',
    password : 'bar',
    database : 'test'
});

// the callback inside connect is called when the connection is good
connection.connect(function(err){
    var sql = "select 'Joe' as name from dual";

    connection.query(sql, function(err, rows, fields) {
        if (err) return console.log(err);
        //  you need to end your connection inside here.
        connection.end();
        console.log(rows[0].name);
    });
});

You will likely start wondering about ways to avoid all these callbacks. You may wish to look at my answer to this question for a more extended mysql example as well as an alternative implementation which offers an alternative to callback-mania.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top