A software library that allows the use of objects and methods to write SQL queries in a database agnostic way.
-
Avoid long concatenated strings in code.
-
Build complex SQL statements programmatically
-
Automatically quotes table names and columns to prevent conflict with SQL reserved words and special characters.
-
Automatically escapes parameters to reduce risk of SQL injection attacks
-
Provides DB abstraction, simplifying migration to different DB platforms
knex init
knexfile.js
Connection strings for various environments
knex migrate:make create_students
migrations folder and CURRENTDATETIME_create_students.js
table.increments()
table.string('name')
knex.schema.createTable('address', function(table) {
t.increments().primary();
table.string('city',50).notNullable();
table.string('state',2).notNullable();
table.integer('zip',5).unsigned().notNullable();
});knex migrate:latest
SELECT * FROM students;knex('students').select();
SELECT * FROM students WHERE id=5; LIMIT 1knex('students').select() .where({id:5}).limit(1);
SELECT * FROM todos
WHERE id IN ('1', '2', '3')
OR user_id IN ('4', '5', '6');knex('todos').whereIn('id', ['1', '2', '3']).orWhereIn('user_id', ['4', '5', '6']);
DELETE * FROM students;knex('students').del();
UPDATE "students" SET "score" = "score" + 10 WHERE id=1;knex('students').where({id:1}) .increment("score",10);
SELECT * FROM "students"
LEFT OUTER JOIN "todos" ON "students"."id" = "todos"."student_id";knex('students').leftOuterJoin('todos', 'students.id', 'todos.student_id');
fin