Search code examples
mysqlnode.jsknex.jsnode-mysql2

Create Knex instance with existing (mysql2) connection


I would like to first create a connection to my database (with mysql2) and then after that create a new Knex instance. I cannot find anything in the documentation about this. Is this even possible?

So, idealy I would like to do something like this (simplified version):

const mysql = require('mysql2');
const Knex = require('knex');

const connection = mysql.createConnection(connectionConfig);
await connection.connect();
const knex = new Knex({
    client: 'mysql2',
    connection: connection,
}):

Solution

  • There is no way to initialize whole knex with connection outside, but you can pass existing connection to knex like:

    const mysql = require('mysql2');
    const Knex = require('knex');
    
    const connection = mysql.createConnection(connectionConfig);
    await connection.connect();
    
    const knex = Knex({
      client: 'mysql2'
    });
    
    // this is documented in knex docs
    const res = await knex('table').connection(connection).where('id', 1);