温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

nodejs个人博客开发第四步 数据模型

发布时间:2020-09-10 22:19:36 来源:脚本之家 阅读:182 作者:陶士涵 栏目:web开发

本文为大家分享了nodejs个人博客开发的数据模型,具体内容如下

数据库模型

/model/db.js 数据库操作类,完成链接数据库和数据库的增删查改

查询表

 /*查询*/ select:function(tableName,callback,where,field){ field=field ? field : '*'; var sql="select "+field+" from "+this.C.DB_PRE+tableName; if(where){ sql+=" where "+where; } this.db.query(sql,callback); } 

添加记录

 /*添加*/ add:function(tableName,tableData,callback){ var sql="insert into "+this.C.DB_PRE+tableName; var clumn=''; var value=''; for(var key in tableData){ clumn+=","+key; value+=",'"+tableData[key]+"'"; } clumns="("+clumn.substr(1)+")"; values="("+value.substr(1)+")"; sql=sql+clumns+"values"+values; console.log(sql); this.db.query(sql,callback); } 

修改记录

 /*修改*/ update:function(tableName,tableData,where,callback){ var sql="update "+this.C.DB_PRE+tableName+" set "; var clumns=""; for(var key in tableData){ clumns+=","+key+"='"+tableData[key]+"'"; } clumns=clumns.substr(1); sql+=clumns+" where "+where; console.log(sql); this.db.query(sql,callback); } 

删除记录

 /*删除*/ delete:function(tableName,where,callback){ var sql="delete from "+this.C.DB_PRE+tableName+" where "+where; console.log(sql); this.db.query(sql,callback); } 

业务模型

例如分类模型,/model/category.js

 /** *分类模型 * */ module.exports={ getAllList:function(){ db.select("category",function(err,list){ console.log(list); }); }, /*添加*/ addCate:function(data){ db.add("category",data,function(err,list){ console.log(err); }); }, /*修改*/ saveCate:function(data,where){ db.update("category",data,where,function(err,list){ console.log(err); }); }, /*删除*/ delCate:function(where){ db.delete("category",where,function(err,list){ //console.log(err); }); } }; 

控制器

先在公共函数文件增加一个调用模型的方法

 /*实例化模型*/ model:function(name){ return require("../model/"+name); } 

控制器调用业务模型

 /** * 首页控制器 */ var router=express.Router(); router.get('/',function(req,res,next){ F.model("category").getAllList(); //F.model("category").addCate({"name":"测试"}); //F.model("category").saveCate({"name":"测试1"},"id=4"); //F.model("category").delCate("id=4"); /*渲染模板*/ res.render("home/index"); }); module.exports=router;

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI