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 SQLpg
: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 PostgreSQLhost
:specify serverport
:specify portuser
:specify idpassword
: specify passworddatabase
:specify databasesearchPath
:specify searching path, tables would be created underpublic
Line 15
let result = await knex ('articles').select ('*')
console.log (result)
Use Knex to generate SQL queries and return the result :
knex
: table for selectselect
:fields for select
Because Knex will return Promise, we have to use top-level await to deal with Promise.
Conclusion
- Just add
Knex
andpg
library, change theclient
topg
, then you can connect to PostgreSQL by Knex