node查询mysql代码(promise)
emer 发布于 2018-5-29 17:20 2347 次阅读
var express = require('express'); var router = express.Router(); var mysql = require('mysql'); var cookieParser = require('cookie-parser'); var session = require('cookie-session'); /* GET home page. */ router.get('/', function(req, res, next) { function select(sql) { var promise = new Promise(function(resolve,reject) { var result = null; var mysql = require('mysql'); var connection = mysql.createConnection({ host: 'localhost', user: 'root', password: 'root' }); connection.connect(); connection.query("USE php");//使用php数据库 connection.query(sql, function (err, results, fields) { if (err) { console.log("err"); reject(err); }else { data=[]; if(results.length > 0) { for(var i=0;i<results.length;i++){ data.push( { txt: results[i].txt, content: results[i].content }); }; //res.write(data); resolve({status:"200",data:data}); }else { resolve({status:"500",data:""}); } } } ); connection.end(); }) return promise; } select("select * from user_n").then(function(data){ res.json(data); res.end(); }).catch(function(){ res.json({err:"数据库连接错误!"}); res.end(); }); }); module.exports = router;