Skip to content
Advertisement

How to connect an existing nodejs server app to Azure SQL database

Can anyone please advise:

I have an existing nodejs server running on azure, running node 10.14 on Linux. The project code is on github and when I push changes they are automatically pushed to azure.

I have set up a database server and database though the Azure portal and can query it through the Azure portal.

I want to modify the nodejs server to conect to the database, I have the connection string code etc. but just the act of adding the line:

var mysql = require('mysql'); 

will stop the server form running as presumably I have not installed mysql on the machine which is running the server in the Azure cloud.

How can I get this to work?

Thanks for any help, Mitch.

Advertisement

Answer

According to the error, you do not add the package in your package.json file and install the package in your project. Besides, if you want to connect Azure SQL server database, we can use package mssqql

For example

  1. My package.json file
{
....
  
    "dependencies": {
        "express": "^4.17.1",
        "mssql": "^6.2.0",
        "request": "^2.88.2"
    }

}
  1. code
const router = express.Router()
const sql = require('mssql')


const config = {

  user: "<user name>",
  password: "<password>",
  server: "<your SQL server name>.database.windows.net",
  port: 1433,
  database: "test",
  connectionTimeout: 3000,
  parseJSON: true,
  options: {
    encrypt: true,
    enableArithAbort: true
  },
  pool: {
    min: 0,
    idleTimeoutMillis: 3000
  }
};
const pool = new sql.ConnectionPool(config);
const poolConnect = pool.connect();

router.get('/', async function (req, res) {
  
  await poolConnect;
  try {
    const request = pool.request(); 
    const result = await request.query('select 1 as number')
    console.log(result);
    res.json(result.recordset);
    
} catch (err) {
    console.error('SQL error', err);
    res.send(err);
}
});
  1. Test.

enter image description here

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement