可以参考菜鸟教程:
http://www.runoob.com/nodejs/nodejs-mysql.html
注意nodejs的数据库操作是异步的,以用户登录为例:
UserDAO.js
~~~
var mysql = require('mysql');
class UserDAO
{
queryUser(name, pwd, cb1, cb2)
{
let connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'root',
port: '3306',
database: 'test',
});
connection.connect();
let sql = "SELECT * FROM userinfo where name =? and pwd = ?";
let addSqlParams = [name, pwd];
connection.query(sql,addSqlParams,function (err, result) {
if(result!='undefined' && result.length!=0)
{
cb1();
}
else
{
cb2();
}
});
connection.end();
}
}
module.exports=UserDAO;
~~~
user.js
~~~
router.post('/login', function(req, res, next) {
let username = req.body.username;
let pwd = req.body.pwd;
var userdao = new UserDAO();
userdao.queryUser(username, pwd, function(){
let u = new userinfo(username, pwd);
//保存session
req.session.account = u;
//设置cookie
res.cookie("account", u, {maxAge: 60000});
res.json(u);
},function(){
res.send("用户不存在");
});
});
~~~