Connecting to MSSQL server with Sequelize

时光怂恿深爱的人放手 提交于 2019-12-10 17:18:58

问题


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


回答1:


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,
        }
    }
  });



回答2:


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
}
[...]



回答3:


Kindly try out what is given in below link, it says that you need to use instanceName property in dialectOptions

https://manuel-rauber.com/2015/11/08/connect-to-ms-sql-using-node-js-and-sequelizejs/




回答4:


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.

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.



来源:https://stackoverflow.com/questions/41819106/connecting-to-mssql-server-with-sequelize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!