我试图通过node.js连接到mysql服务器(host:localhost),我是node.js的新手,我不知道如何做到这一点,请帮助!
我用来连接服务器的当前代码
var client = require('socket.io').listen(8080).sockets,
mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'testDatabase',
port : '3306'
});
connection.connect();
var strQuery = 'select * from users';
connection.query( strQuery, function(err, rows){
if(err){
throw err;
}else{
console.log(rows);
}
});
connection.end();
显然给出了以下错误
Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'prashanthsun9'@'localhost
' (using password: YES)
at Handshake.Sequence._packetToError (C:\wamp\www\node_chat\js\node_modules\
mysql\lib\protocol\sequences\Sequence.js:30:14)
at Handshake.ErrorPacket (C:\wamp\www\node_chat\js\node_modules\mysql\lib\pr
otocol\sequences\Handshake.js:99:18)
at Protocol._parsePacket (C:\wamp\www\node_chat\js\node_modules\mysql\lib\pr
otocol\Protocol.js:205:24)
at Parser.write (C:\wamp\www\node_chat\js\node_modules\mysql\lib\protocol\Pa
rser.js:62:12)
at Protocol.write (C:\wamp\www\node_chat\js\node_modules\mysql\lib\protocol\
Protocol.js:37:16)
at Socket.<anonymous> (C:\wamp\www\node_chat\js\node_modules\mysql\lib\Conne
ction.js:73:28)
at Socket.EventEmitter.emit (events.js:95:17)
at Socket.<anonymous> (_stream_readable.js:746:14)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
--------------------
at Protocol._enqueue (C:\wamp\www\node_chat\js\node_modules\mysql\lib\protoc
ol\Protocol.js:110:48)
at Protocol.handshake (C:\wamp\www\node_chat\js\node_modules\mysql\lib\proto
col\Protocol.js:42:41)
at Connection.connect (C:\wamp\www\node_chat\js\node_modules\mysql\lib\Conne
ction.js:99:18)
at Object.<anonymous> (C:\wamp\www\node_chat\js\server.js:11:12)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
请帮助,请帮助!!!
答案 0 :(得分:0)
尝试查询时尚未设置连接。 要进行调试,请更改以下行:
connection.connect();
到
connection.connect(function(err, conn) {
if(err) {
console.log('MySQL connection error: ', err);
process.exit(1);
}
});
所以你会得到你的连接不正确的错误跟踪。
答案 1 :(得分:0)
尝试将您的npm mysql
版本升级为^2.1.1
。