Loading

Knex框架的使用

knex框架的使用

1.1什么是knex

knex框架是一个ORM框架,使用knex可以用JavaScript语法指令来操作SQL语句,这大大降低了前端工程师操作进行数据库操作的难度,但是需要注意的是knex最终还是会生成SQL语句和数据库进行交互

1.2knex的安装

在编辑器终端输入npm install mysql

再输入npm install knex

也可以进行简写npm install mysql knex

1.3导包

//导包
const knex = require('knex')({
  client: 'mysql', //指定knex要操作的数据库为MySQL
  connection: {
    host : '127.0.0.1', //数据库地址
    user : 'your_database_user', //数据库登录名
    password : 'your_database_password',//数据库登录密码
    database : 'mydata' //要操作的库名称
  }
});

2.使用knex操作数据库

特性:可以使用链式语法,因为knex使用的Promise,所以最后需要一个then()和catch(),这两个都传入一个回调函数,

.then(result => {
         查询成功之后执行,参数result就是执行之后的结果.
}).catch(error => {
          查询失败之后执行,参数error是失败的原因
})

2.1查询所有数据

//语法
knex('表名').select().then(result => {
    
}).catch(error => {
    
})
//1.表名:你需要操作的表名称
//2.select方法传入需要查询的字段名,如果不传,代表全部字段查询.
//3.查询成功后,会调用then中的回调.参数result就是查询的结果.
//4.当查询失败时,就会调用catch中的回调.  error就是失败的信息.

2.2单条件查询

//语法,紧跟在select之后
knex('表名').select().where().then().catch();
 select().orWhere('nickname', 'like', '%' + q + '%')
 最终reults返回的是一个数组

2.3多条件查询

//语法
knex('表名').select().where().andWhere();
knex('表名').select().where().orWhere();

knex('student')
    .select()
    .where('name','like', '%花%')
    .orWhere('nickname','like', '%花%')
    .andWhere({isDel: 0})
    .then(result=>{
        console.log(result)
    })
    .catch(reason => {
        console.log(reason)
    })
最终reults返回的是一个数组

2.4增加数据

// insert方法传1个对象,对象的属性和数据库的字段对应.
knex('表名').insert(obj)

knex('student').insert({
    name: "王侃侃",
    nickname: "豆豆",
    gender: "男",
    age: 6,
    score: 99,
    className: "阳光幼儿园大班",
    avator: "default_avator.png"
}).then(result=>{
    console.log(result)
}).catch(reason => {
        console.log(reason)
})
//result返回值是新增的数据的id

2.5删除数据

//返回值是影响的行数,通过返回值可以对函数再作判断
knex('student').delete()
    .where({id: 14})
    .then(result => {
    	console.log(result)
	})
    .catch(reason => {
    	console.log(reason)
})

2.6修改数据

//返回值是影响的行数,通过返回值可以对函数再作判断
knex('student').update({
    name: "李逵"
}).where({id: 12}).then(result => {
    console.log(result)
}).catch(reason => {
    console.log(reason)
})

2.7 分页查询

//根据关键字从数据库查询符合条件的数据.

module.exports.getStudentsByQ = (q, pageIndex, callbackSuccess, callbakError) => {
knex('student').select().where('name', 'like', '%' + q + '%')
        .orWhere('nickname', 'like', '%' + q + '%')
        .limit(config.pageSize)//限制每页数量
        .offset((pageIndex - 1) * config.pageSize)//限制索引页面的数据
        .then(results => {
            callbackSuccess(results);
        })
        .catch(reason => {
            callbakError(reason);
        })
}
posted @ 2021-05-27 21:01  大黄树  阅读(2683)  评论(0)    收藏  举报