Using sequel pro I have created a database called test. It has one table called users. In that table there is one user -> id=1, name=Phantom.

When I run the code below I get The solution is: undefined.

Can anyone advise how I can connect to database and show the users?

var mysql = require('mysql');

var connection = mysql.createConnection({

host : 'localhost:8889',

user : 'root',

password : 'root',

database : 'test'

});

connection.connect();

connection.query('SELECT * from users', function(err, rows, fields) {

if (err) throw err;

console.log('The solution is: ', rows);

});

connection.end();

It shows the following error :

Error: connect ETIMEDOUT

at Connection._handleConnectTimeout (/Users/fitz035/Desktop/sony/presave/node_modules/mysql/lib/Connection.js:425:13)

I am running the db through MAMP. These are the db settings :

Host: localhost

Port: 8889

User: root

Password: root

Socket: /Applications/MAMP/tmp/mysql/mysql.sock

解决方案

Node is asynchronous, so connection.end() is likely to happen before your query calls back. Also, specify the port Mysql is running on when non-standard.

try this :

var mysql = require('mysql');

var connection = mysql.createConnection({

host : 'localhost',

user : 'root',

password : 'root',

database : 'test',

port: 8889

});

connection.connect();

connection.query('SELECT * from users', function(err, rows, fields) {

if(err) console.log(err);

console.log('The solution is: ', rows);

connection.end();

});

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐