Search code examples
javascriptmysqlnode.jsappfognode-mysql

Appfog with node.js how to access with javascript to mysql databases?


I have one node.js application published in appfog, but when I try to access a mysql database through javascript with ( https://github.com/felixge/node-mysql ), "node-mysql" seems that is not installed, what is the way to do this? there is no documentation on appfog site. thanks.

the code of server app.js:

if(process.env.VCAP_SERVICES){
var env = JSON.parse(process.env.VCAP_SERVICES);
var cre = env['mysql-5.1'][0]['credentials'];
}
var Client = require('mysql').Client,
client = new Client();
client.user = cre.user;
client.password = cre.password;
client.host=cre.host;
client.port=cre.port;
client.database=cre.name;
client.connect();

client.query(
    'SELECT * FROM scores ',
    function selectPlayers(err, results, fields) {
        if (err) {
            console.log("Error: " + err.message);
            throw err;
        }
        console.log("Number of rows: "+results.length);
        console.log(results);
        client.end();
    });

and the error:

module.js:340
throw err;
      ^
Error: Cannot find module 'mysql'
at Function.Module._resolveFilename (module.js:338:15)

Solution

  • you should add

    "mysql": "2.0.x || 2.1.x",
    

    to the dependencies in your package.json file, and then do

    npm install
    

    You can check out Appfog's documentation here. There is a section about dependency management