Enter data with SQL SERVR in node.js [closed]

-1

I would like someone to give me an example of how I can enter data in a SQL SERVER database from Node.js please!

Thanks:)

    
asked by java005 04.09.2018 в 18:34
source

1 answer

0

I have used this library for SQLServer many times, it is called mssql and I have no problems

Before starting you should have an instance of SQL running, and the credentials with which you will do any function, be it a CRUD or execution of a SP .

First of all you must install the library using:

npm install mssql

Define the configuration

const config = {
    user: '...',
    password: '...',
    server: 'localhost', //IP o Nombre de equipo según conf. del MSSQL
    database: '...' //Nombre de la BD
}

In a function that:

  • Open the connection.
  • Receive parameters.
  • Execute an SP.
  • Close connection.
  • It helps you:

     exports.execSP = function(req, res)
        {
            console.log("(iExSP)LOG_:exec-SP");
            sql.connect(config, function (err) {
            if (err)
            {
                console.log("(eExSP)LOG_:exec-SP"+err.originalError);
                res.status(500).send(err.originalError);
            }
            else
            {
                var request = new sql.Request();
                request.input('varOne', req.body.varTwo);
                request.input('varTwo', req.body.varTwo);
                request.execute('SP_Nombre', (err, result) => {
                    if(err){console.log("LOG_:exec-SP"+' '+err.originalError.info.message);
                        res.status(500).send(err.originalError.info)}
                    else
                    {
                        if(result.recordsets[0].length == 0)
                        {
                            var recordsets = [{"msg":" No Data"}];
                            console.log("LOG_:exec-SP"+' '+recordsets[0].msg);
                            res.status(204).send(recordsets[0].msg)
                        }
                        else
                        {
                            console.log("LOG_:exec-SP Data Sent");
                            res.status(200).send(result.recordsets[0])
                        }
                    }
                    sql.close()
                })  
            }                   
            })
        };
    
        
    answered by 04.09.2018 / 23:24
    source