點燈坊

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

Using Knex to Connect to MySQL

Sam Xiao's Avatar 2021-11-07

We can use Knex to connect to MySQL, jsut install MySQL library.

Version

Knex 0.95.11
MySQL 8.0.26

Knex

$ yarn add knex mysql
  • knex:SQL builder to generate SQL
  • mysql:MySQL library
import Knex from 'knex'

let knex = Knex ({
  client: 'mysql',
  connection: {
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '111111',
    database: 'DBLab'
  }
})

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

LIne 3

let knex = Knex ({
  client: 'mysql',
  connection: {
    host: 'localhost',
    port: 3306,
    user: 'root',
    password: '111111',
    database: 'DBLab'
  }
})

Use Knex to connect to database :

  • client: 'mysql' : connect to MySQL
  • 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.

mysql000

Conclusion

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

Reference

Knex, Intallation