Can't connect to localhost database from node.js server

若如初见. 提交于 2019-12-06 02:17:55

It's most likely that networking is turned off, that means that mysql server communicates with clients via UNIX sockets and not via TCP/IP. You can check that out running mysql client and run "status" command. If you see port number there, then your mysql server communicates via TCP/IP, or else you'll see something like "socket pathname…", get the pathname and give it to node.js connection parameters, e.g.

... socketPathname: '/opt/lampp/var/...', ...

Check that out in https://github.com/felixge/node-mysql page (search for "socketPathname")

Hope, that's your problem.

change this

database.init('uber', 'pass', 'mysql', 'localhost', 8000);

to

database.init('uber', 'pass', 'mysql', 'localhost', 3306);

and you should be through

Make sure that MySQL and express are running on the same port. I had MySQL bundled from XAMPP, that ran on Port 3036. On setting app.listen to 3036, my code worked. FINALLY!

You should use mysql_config to show the path to socket.
This a sample on my MAC

QuyLes-MacBook-Pro:freelancer quyle$ mysql_config
Usage: /Applications/MAMP/Library/bin/mysql_config [OPTIONS]
Options:
        --cflags         [-I/Applications/MAMP/Library/include -fno-omit-frame-pointer   -g -DNDEBUG]
        --include        [-I/Applications/MAMP/Library/include]
        --libs           [-L/Applications/MAMP/Library/lib  -lmysqlclient  -lz]
        --libs_r         [-L/Applications/MAMP/Library/lib   -lmysqlclient_r  -lz]
        --plugindir      [/Applications/MAMP/Library/lib/plugin]
        --socket         [/Applications/MAMP/tmp/mysql/mysql.sock]
        --port           [0]
        --version        [5.5.42]
        --libmysqld-libs [-L/Applications/MAMP/Library/lib  -lmysqld]
        --variable=VAR   VAR is one of:
                pkgincludedir [/Applications/MAMP/Library/include]
                pkglibdir     [/Applications/MAMP/Library/lib]
                plugindir     [/Applications/MAMP/Library/lib/plugin]

and then, you add key socketPath for yourMysqlConnection.
bellow on my sample

MysqlServer: {
     adapter: 'sails-mysql',
     host: 'localhost',
     user: 'root', //optional
     password: 'root', //optional
     database: 'nodejs', //optional,
     socketPath: '/Applications/MAMP/tmp/mysql/mysql.sock'    
},

Try this code it's work for me

var mysql = require('mysql');

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

connection.connect();


query = connection.query("SELECT * FROM UrTable;");
    query
    .on('error', function(err) {
        console.log( err );

    })
    .on('result', function( data ) {
        socket.emit('YourData',data);
    });

I hope this will be helpful for you

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!