Urasquirrel
Urasquirrel

Reputation: 1585

Connect to SQL Server with knexjs, Unable to acquire a connection

After trying looking at dozens of examples, and reading most of the docs, and trying many different variations, and changing many settings within SQL Server, I've finally broke down to ask for help with this one.

I successfully connected to a tblTextKnex with mssqljs using the exact same connection string which SQL Server accepts, but have not been able to with knexjs for some time now.

I get the following warning and error:

Knex:warning - calling knex without a tableName is deprecated. Use knex.queryBuilder() instead.

and

Unhandled rejection Error: Unable to acquire a connection

This is the unsuccessful/offending code that I believed should work.

  var knex = require('knex')({
    client: 'mssql',
    connectionString: "Initial Catalog=TextKnex;Data Source=localhost\\TESTINSTANCE;User ID=my_user_id;Password=my_password;Integrated Security=SSPI;"
  });

  knex().connection().then(() => {
     knex('TextKnex').table('Products')
        .select('Products.Price as Price')
        .then((product) => {
            console.log('log product', product);
            console.dir('dir product', product);
            logger.info('Query Data: %j', product);
     })
  });
  knex.destroy();

Upvotes: 0

Views: 9355

Answers (1)

Mikael Lepistö
Mikael Lepistö

Reputation: 19718

I'm pretty sure, there is no connectionString attribute and connection() query builder method is documented to not work (and is not checking if pool has been connected). Also synchronously called knex.destroy() in the end destroys your knex instance, before any queries or connections would have been made.

Try this:

  var knex = require('knex')({
    client: 'mssql',
    connection: {
      connectionString: "Initial Catalog=TextKnex;Data Source=localhost\\TESTINSTANCE;User ID=my_user_id;Password=my_password;Integrated Security=SSPI;"
    }
  });

  knex('TextKnex').table('Products')
    .select('Products.Price as Price')
    .then((product) => {
      console.log('log product', product);
      console.dir('dir product', product);
      logger.info('Query Data: %j', product);
    })
    .finally(() => {
      knex.destroy();
    });

or

  var knex = require('knex')({
    client: 'mssql',
    connection: "Initial Catalog=TextKnex;Data Source=localhost\\TESTINSTANCE;User ID=my_user_id;Password=my_password;Integrated Security=SSPI;"
  });

  ...

In knex tests mssql connection is done a bit different way: https://github.com/tgriesser/knex/blob/master/test/knexfile.js#L132

Upvotes: 2

Related Questions