当前位置:Gxlcms > 数据库问题 > [转]在node.js中,使用基于ORM架构的Sequelize,操作mysql数据库之增删改查

[转]在node.js中,使用基于ORM架构的Sequelize,操作mysql数据库之增删改查

时间:2021-07-01 10:21:17 帮助过:23人阅读

  1. User.create({
  2. name: ‘XiaoMing‘,
  3. password: ‘1234567890‘,
  4. mail: ‘xiaoming@qq.com‘
  5. }).then(function(result){
  6. console.log(‘inserted XiaoMing ok‘);
  7. }).catch(function(err){
  8. console.log(‘inserted XiaoMing error‘);
  9. console.log(err.message);
  10. });
技术图片

 

查询记录

调用模型对象的findAll方法进行查询操作,在参数中可以制定where条件。

where条件甚至可以支持数据库自身特有的函数。

where具体写法,参考:http://sequelize.readthedocs.io/en/latest/docs/querying/

技术图片
  1. User.findAll({
  2. where:{
  3. name:{
  4. $like:‘Zhang%‘
  5. }
  6. }
  7. }).then(function(result){
  8. console.log(‘query all users‘);
  9. for (var i = 0, usr; usr = result[i++];) {
  10. console.log(‘nae=‘ + usr.name + ‘, password=‘ + usr.password + ‘, mail=‘ + usr.mail);
  11. }
  12. });
技术图片

 

修改记录

调用模型对象的update方法进行更新操作,在第一个参数中指定更新的字段和值,在第二个参数中指定条件。

技术图片
  1. User.update({
  2. password:‘12‘
  3. },{
  4. where:{
  5. name:{
  6. $like:‘Xiao%‘
  7. }
  8. }
  9. }).then(function(result){
  10. console.log(‘updated user‘);
  11. console.log(result);
  12. });
技术图片

 

删除记录

调用模型对象的destroy方法进行删除操作,在参数中指定删除条件。

技术图片
  1. User.destroy({
  2. where:{
  3. name:{
  4. $like:‘Zhang%‘
  5. }
  6. }
  7. }).then(function(result){
  8. console.log(‘destroy user‘);
  9. console.log(result);
  10. });
技术图片

 

官方文档:戳

[转]在node.js中,使用基于ORM架构的Sequelize,操作mysql数据库之增删改查

标签:dial   upd   lan   数据   read   增删改   技术   查询   开源   

人气教程排行