express 使用knex连接数据库(增删改查)

1. 使用knex

npm install knex mysql --save

2. 连接数据库

const knex = require('knex')({
    client: 'mysql', 
    connection: {
      host: 'localhost', // 地址
      user: 'root', // 账号
      password: '123456', // 密码
      database: 'app', // 数据库
      // options: {
      //   port: 3306 // 端口
      // }
    }
  });
  module.exports = knex;

3. knex增删改查

knex(‘表名’)

knex增加

let data = {
    name: '小米nu',
    val: '13'
  }
knex('user').insert(data).then(result=>{
        console.log(result)
        res.send(data)
    }).catch(reason => {
        console.log(reason)
    })

knex删

knex('user')
.where('name','小明')
.del().then(result=>{
        console.log(result)
        res.send(data)
    }).catch(reason => {
        console.log(reason)
    }) 

knex改

knex('user')
.where('age','<',18)
.update({
    age: 18
}).then(result=>{
        console.log(result)
        res.send(data)
    }).catch(reason => {
        console.log(reason)
    })

knex查询

knex('user')
.where({name:'小明',val:16})
.select().then(result=>{
        console.log(result)
        res.send(data)
    }).catch(reason => {
        console.log(reason)
    })

where的用法

where(object)   // 符合多项规则时用传入对象
where(key:value) //符合单一规则传入键值对更简便
where(key,操作符,value) //符合单一特殊规则时如x>100时使用
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容