點燈坊

失くすものさえない今が強くなるチャンスよ

Using Knex to Connect to MSSQL

Sam Xiao's Avatar 2021-11-07

We can use Knex to connect to MSSQL, jsut install Tedious library.

Version

Knex 0.95.11
Tedious 14.0.0
MSSQL 2017

Add Library

$ yarn add knex tedious
  • knex : SQL builder to generate SQL
  • tedious : MSSQL library

Knex

import Knex from 'knex'

let knex = Knex ({
  client: 'mssql',
  connection: {
    host: '10.211.55.7',
    port: 1433,
    user: 'sa',
    password: '111111',
    database: 'DBLab'
  }
})

let result = await knex ('articles').select ('*')
console.log (result)

Line 3

let knex = Knex ({
  client: 'mssql',
  connection: {
    host: '10.211.55.7',
    port: 1433,
    user: 'sa',
    password: '111111',
    database: 'DBLab'
  }
})

Use Knex to connect to database :

  • client: 'mssql' : connect to MSSQL
  • host:setup server
  • port:setup port
  • user:setup id
  • password:setup password
  • database:setup database

Line 14

let result = await knex ('articles').select ('*')
console.log (result)

Use Knex to generate SQL query and return result :

  • knex : table for select
  • select :fields for select

Becuase Knex will return Promise, we have to use top-level await to deal with Promise.

mssql000

Conclusion

  • Just add Knex and tedious library, change client to mssql, then you can connect to MSSQL by Knex