It is amazing that how much trouble I had trying to establish connection to local mysql server. A quick search on StackOverflow shows that I am not alone!
I think I found a surefire way to establish local mysql connections – use socket instead of TCP/IP. Briefly, there are two ways to establish mysql connections, either with TCP/IP (you need host and port number) or socket (you only need the filepath of the socket).
In theory, there shouldn’t be much difference between them. However, finding a file is definitely easier than finding the ip and the port number.
Here is the code to connect to a Mysql db from MAMP.
var mysql = require('mysql'); var connection = mysql.createConnection({ user : 'root', password : "root", socketPath : '/Applications/MAMP/tmp/mysql/mysql.sock', //for non MAMP, might be //socketPath : '/tmp/mysql.sock', }); connection.connect(function(err) { if (err) { console.log('db_connection_err', err); return; } }); connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution); }); connection.end();