Alan Thomas
Alan Thomas

Reputation: 1034

Connecting to MSSQL server with Sequelize

Using the following tedious code, I can successfully connect to an Azure SQL Server.

const Connection = require('tedious').Connection;

const connection = new Connection({
    userName: '[USER]',
    password: '[PASSWORD]',
    server: '[HOSTNAME]',
    options: {encrypt: true}
});

connection.on('connect', (err) => {
    if (err) {
        console.log('error connecting', err);
    } else {
        console.log('connection successful');
    }
});

However, using what should be the equivalent Sequelize code, I get a connection timeout error.

const Sequelize = require('sequelize');

const sequelize = new Sequelize('[DBNAME]', '[USER]', '[PASSWORD]', {
    dialect: 'mssql',
    host: '[HOSTNAME]',
    dialectOptions: {
        encrypt: true
    }
});

sequelize.authenticate().then((err) => {
    console.log('Connection successful', err);
})
.catch((err) => {
    console.log('Unable to connect to database', err);
});

Any thoughts?

Using: sequelize 3.29.0, tedious 1.14.0, SQL Server v12

Upvotes: 11

Views: 26522

Answers (4)

wajahat12345
wajahat12345

Reputation: 27

if you are using sql server management studio then simply replace dialect:'mysql' with dialect:'mssql':

 const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
    host: 'Host',
    dialect: 'mssql',
    dialectOptions: {
        options: {
            encrypt: true,
        }
    }
  });

Upvotes: -1

Vinay Bhawsar
Vinay Bhawsar

Reputation: 181

I was getting below error

SequelizeConnectionError: Server requires encryption, set 'encrypt' config option to true.

I tried it out with Azure SQL Database and below way is working for me.

const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
    host: 'Host',
    dialect: 'mssql',
    dialectOptions: {
        options: {
            encrypt: true,
        }
    }
  });

Upvotes: 18

Luis Bosquez
Luis Bosquez

Reputation: 386

If you're trying it out with Azure SQL Database, you might also want to specify a longer request timeout value:

[...]
dialectOptions: {
    requestTimeout: 30000 // timeout = 30 seconds
}
[...]

Upvotes: 6

Aaron Chen
Aaron Chen

Reputation: 9950

I tried your Sequelize code and it works fine. So you might need to add Client IP address to allow access to Azure SQL Server. To do this, go to the Azure portal, click on All Resources, select your SQL server, click on Firewall in the SETTINGS menu.

enter image description here

Your client address is conveniently included in the list, so you can just click on Add client IP followed by Save. When you run your code now, it should connect.

Upvotes: 1

Related Questions