How to connect the MSSQL server with Hapi.js?

Sometimes we need to get data from MSSQL server using Hapi framework. Then we achieve this by installing the external plugin called mssql.

1. Install the mssql plugin to your hapi project.

$ npm install mssql

2. Check the query and store procedure example below.

var sql = require("mssql"); 
var config = {
        user: "<replace-your-username>",
        password: "<replace-your-password>",
        server: "<replace-your-serverip>", 
        database: "<replace-your-database-name>",
        "options": {          
            "enableArithAbort": true
        }        
};
(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // ... error checks
    }
})()
 
sql.on('error', err => {
    // ... error handler
})

That’s it. I hope this will help. ?
Ref : https://www.npmjs.com/package/mssql

Leave a Reply

Your email address will not be published. Required fields are marked *