Node.js连接数据库前,需要安装相应的包,如果安装sql server 需要先装包node-sqlserver。我们以mysql为案例来说明node.js查询mysql数据。
1、安装 node-mysql
npm install node-mysql
2、通过express框架实现数据库连接
var express = require('express'); var mysql = require('mysql'); var app = express(); app.use(function(req, res, next){ console.log('%s %s', req.method, req.url); next(); }); var conn = mysql.createConnection({ host:'localhost', user:'root', database:'ceshi', password:'123456', port:3306 }); conn.connect(); app.get('/', function(req, res){ conn.query('SELECT * from ceshibiao', function(err, rows, fields) { if(err) throw err; var data = ''; foreach(rows,function(key,value){ data += '<p>' + 'contents:' + value.contents + '</p>'; data += '<hr />'; } res.send(data); }); }); app.listen(81); console.log('Listening on port 81');
原文地址:http://blog.csdn.net/zhao1234567890123456/article/details/39034037