點燈坊

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

Using Knex to INSERT Data

Sam Xiao's Avatar 2021-11-04

Although we can use raw SQL INSERT, but it’s more concise to use Knex to insert data.

Version

Knex 0.95.12
PostgreSQL 14.0

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')
  .insert ({
    'title': 'Title 1',
    'content': 'Content 1'
  }, ['*'])

console.log (result)

Line 15

let result = await knex ('articles')
  .insert ({
    'title': 'Title 1',
    'content': 'Content 1'
  }, ['*'])

Use Knex to generate SQL INSERT and return result :

  • knex : table to insert
  • insert : Object to insert, key is field and value is data
  • ['*'] : return whole Object after inserted, this is optional

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

insert000

Conclusion

  • Insert Object is more intuitive than raw SQL INSERT, and more concise

Reference

Knex, Insert