nodejs之mysql查询
示例代码中的mysql版本 2.14.1
参考代码
1 /** 2 * 测试mysql连接 3 */ 4 5 var mysql = require('mysql'); 6 var connection = mysql.createConnection({ 7 host : 'localhost', //服务器 8 user : 'root', //用户名 9 password : 'root', //密码 10 database : 'mysql' //数据库 11 }); 12 connection.connect(function(err) { 13 if(err) { 14 console.error('error connecting: ' + err.stack); 15 return; 16 } 17 console.log('connected as id ' + connection.threadId); 18 }); 19 20 var http = require('http'); 21 22 var server = http.createServer(function(request, response){ 23 response.writeHeader(200, {'Content-type': 'text/html'}); 24 // 查询User为root的用户 25 connection.query('SELECT * FROM user WHERE User = ?', ['root'], function(err, results, fields){ 26 if(err) { 27 throw err; 28 } 29 var data = ''; 30 for (var i = 0; i < results.length; i++) { 31 var firstResult = results[i]; 32 data += 'User: '+ firstResult['User'] + ' Password: ' + firstResult['Password'] + '<br>'; 33 } 34 35 response.write(data); 36 response.end(); 37 38 }); 39 }); 40 41 server.listen(8080); 42 43 var sys = require('util'); 44 sys.puts('Server running at http://localhost:8080/');