技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機(jī)純凈版,64位旗艦版,綠色軟件,免費(fèi)軟件下載基地!

當(dāng)前位置:主頁 > 教程 > 服務(wù)器類 >

nodejs個人博客數(shù)據(jù)模型開發(fā)教程

來源:技術(shù)員聯(lián)盟┆發(fā)布時間:2017-11-07 06:32┆點(diǎn)擊:

  數(shù)據(jù)庫模型

  /model/db.js 數(shù)據(jù)庫操作類,完成鏈接數(shù)據(jù)庫和數(shù)據(jù)庫的增刪查改

  查詢表

  /*查詢*/

  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);

  }

  業(yè)務(wù)模型

  例如分類模型,/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);

  });

  }

  };

  控制器

  先在公共函數(shù)文件增加一個調(diào)用模型的方法

  /*實(shí)例化模型*/

  model:function(name){

  return require("../model/"+name);

  }

  控制器調(diào)用業(yè)務(wù)模型

  /**

  * 首頁控制器

  */

  var router=express.Router();

  router.get('http://www.3lian.com/',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;