Quantcast
Channel: IT社区推荐资讯 - ITIndex.net
Viewing all articles
Browse latest Browse all 15843

Node.js连接数据库

$
0
0

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');
作者:Zhao1234567890123456 发表于2014-9-3 22:31:21 原文链接
阅读:0 评论:0 查看评论

Viewing all articles
Browse latest Browse all 15843

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>