點燈坊

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

Using Knex to Connect to PostgreSQL

Sam Xiao's Avatar 2021-11-26

We can use Knex to connect to PostgreSQL; just install the Node-postgres library.

Version

Knex 0.95.11
Node-postgres 8.7.1
PostgreSQL 14.0

Add Library

$ yarn add knex pg
  • knex:SQL builder to generate SQL
  • pg:PostgreSQL library

Knex

import Knex from 'knex'

let knex = Knex ({
  client: 'pg',
  connection: {
    host: 'localhost',
    port: 5432,
    user: 'admin',
    password: '12345',
    database: 'DBLab'
  },
  searchPath: ['public']
})

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

Line 3

let knex = Knex ({
  client: 'pg',
  connection: {
    host: 'localhost',
    port: 5432,
    user: 'admin',
    password: '12345',
    database: 'DBLab'
  },
  searchPath: ['public']
})

Use Knex to connect to database :

  • client: 'pg' : connect to PostgreSQL
  • host:specify server
  • port:specify port
  • user:specify id
  • password: specify password
  • database:specify database
  • searchPath:specify searching path, tables would be created under public

Line 15

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

Use Knex to generate SQL queries and return the result :

  • knex : table for select

  • select :fields for select

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

postgre000

Conclusion

  • Just add Knex and pg library, change the client to pg, then you can connect to PostgreSQL by Knex