最新消息: 新版网站上线了!!!

node.js使用mysql的简单方法

第一步:新建一个 package.json

{
  "name": "news",
  "version": "0.0.0",
  "private": true,
  "scripts": {
    "start": "node ./bin/www"
  },
  "dependencies": {
    "body-parser": "~1.13.2",
    "cookie-parser": "~1.3.5",
    "debug": "~2.2.0",
    "express": "~4.13.1",
    "jade": "~1.11.0",
    "morgan": "~1.6.1",
    "mysql": "^2.12.0",
    "serve-favicon": "~2.3.0"
  }
}

第二步:npm install mysql -save

第三步:

var mysql      = require('mysql');
var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  password : '',
  database : 'cms'
});
connection.connect();
var http = require('http');

var data = [];
connection.query('SELECT * FROM area limit 0,10', function(err, rows, fields) {
  if (err) throw err;
  data = rows;
  console.log('The solution is: ', rows);
});
var srv = http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'application/json'});
  res.end(JSON.stringify(data));
});
srv.listen(8080, function() {
  console.log('listening on localhost:8080');
}); 
connection.end();

第四步:输入网址http://localhost:8080

下载源码 下载地址

.....

转载请注明:谷谷点程序 » node.js使用mysql的简单方法