Node.js开发 ---- nodejs操作mysql

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Node.js开发 ---- nodejs操作mysql相关的知识,希望对你有一定的参考价值。

app.js
[html] view plain copy
//初始化包
var express = require(‘express‘);
var path = require(‘path‘);
var favicon = require(‘serve-favicon‘);
var logger = require(‘morgan‘);
var cookieParser = require(‘cookie-parser‘);
var bodyParser = require(‘body-parser‘);
var mysql = require("mysql");
var jade = require(‘jade‘);
var routes = require(‘./routes/index‘);

var app = express();

//加载引擎模板
app.set(‘view engine‘, ‘jade‘);
app.set(‘views‘, path.join(__dirname, ‘views‘));

//调用工具
app.use(logger(‘dev‘));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, ‘public‘)));

routes(app);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error(‘Not Found‘);
err.status = 404;
next(err);
});

// will print stacktrace
if (app.get(‘env‘) === ‘development‘) {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render(‘error‘, {
message: err.message,
error: err
});
});
}

// no stacktraces leaked to users
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render(‘error‘, {
message: err.message,
error: {}
});
});

app.listen(3000);

[html] view plain copy 在CODE上查看代码片派生到我的代码片
var user = require("../models/user.js");

module.exports = function (app) {
app.post(‘/updateUsers‘, function (req, res, next) {
user.updateUsers({
sql: "update user SET username=?,password=?,age=?,info=? WHERE id = ?",
params: [ req.body.username, req.body.password, req.body.age, req.body.info, req.body.id ]
}, function (data) {
res.send(data);
});
});

app.post(‘/deleteUsers‘, function (req, res, next) {
user.deleteUsers({
sql: "DELETE FROM user WHERE id = " + req.body.id
}, function (data) {
res.send(data);
});
});

app.post(‘/addUsers‘, function (req, res, next) {
user.addUsers({
data: {
username: req.body.username,
password: req.body.password,
age: req.body.age,
info: req.body.info
},
sql: "INSERT INTO user SET ?"
}, function (data) {
res.send(data);
});
});
};


























































































以上是关于Node.js开发 ---- nodejs操作mysql的主要内容,如果未能解决你的问题,请参考以下文章

Nodejs的模块化

Nodejs的模块化

Nodejs学习笔记--- 简介及安装Node.js开发环境

Nodejs学习笔记--- 简介及安装Node.js开发环境

VS Code nodejs远程调试:断点被忽略

计算机毕业设计基于node.js中小企业合同管理系统