knex / knex

A query builder for PostgreSQL, MySQL, CockroachDB, SQL Server, SQLite3 and Oracle, designed to be flexible, portable, and fun to use.
https://knexjs.org/
MIT License
19.16k stars 2.11k forks source link

Unclear how I connect to an existing db and pull a record #5973

Open jcollum-nutrien opened 1 year ago

jcollum-nutrien commented 1 year ago

Just saying. The docs are cryptic. If I have an existing database and want to use Knex to get a record from it... not sure what to do. Doubly so since I'm using Typescript.

zanonnicola commented 1 year ago

I think this is more a StackOverflow question honestly (IMHO). Anyway you can do something like this:

import { knex, Knex } from 'knex';

const pool: Knex = knex({
      client: 'pg',
      connection: {
        connectionString: 'postgresql://postgres:mysecretpassword@localhost:5432/my-db',
        pool: {
          min: 0, // It is recommended to set min: 0 so all idle connections can be terminated. https://knexjs.org/guide/#pool
          max: 50,
        },
      },
    });

And then use it:

const result = await pool
      .select('*')
      .from('table')
      .first();