NODE.js Insert in MS SQL

Asked

Viewed 1,010 times

-2

I am trying to run an INSERT in my MSSQL through my NODE.js server But it’s not working.

I believe it is not a connection problem because (as I will demonstrate at the end of the post) I made a select that worked.

then I must be making a mistake in the Node.js code

This is the first javascript system I created.

    var express = require('express');
var app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', function (req, res) {
    var body = req.body;
    var sql = require("mssql");

             console.log("C1");
     sql.connect('mssql://login:senha@servidor/banco', function (err) {

        if (err) console.log(err);

        // create Request object
         console.log("Connected!");
        var insert = "INSERT into dbo.WIDS_API_TEST (Programm, ID, Titlw) VALUES ('Teste 1 2 3 ', '39', 'Finance')"

        // query to the database and get the records
        sql.query(insert, function (err, result) {

            if (err) console.log(err)

            // send records as a response
        console.log("1 record inserted");

        });
    });
});

//var server = app.listen(5000, function () {
  //  console.log('Server is running..');
//});

What am I doing wrong? Because INSERT didn’t even show my console. = /  

When I did a test doing a select worked

   var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
/*    var config = {
        user: 'papercut',
        password: 'Portage.2018',
        server: 'devsqlcl2:1433', 
        database: 'AgrM6',
        port: "1433",
        dialect:",ssql",
        dialectOptiond:"SQLEXPRESS"
    };*/

    // connect to your database
    sql.connect('mssql://loginh:senha@server/banco', function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records
        request.query('select * from dbo.balance_papercut', function (err, recordset) {

            if (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

!! THIS WORKED, IS THE SELECT!!

  • Check if the user you used to connect to the WIDS database has permission to read (write) in the table WIDS_API_TEST.

  • Yes, I highlighted this test , right at the bank and it works, I updated the question to make it easier and less confusing

  • What error is shown? I will rewrite this code of yours to make it less confusing

  • Take a look at the code I will post here in the comment and inform in your question the error that is returned in the console, but at first the name of your columns is wrong https://pastebin.com/X5xL8pdX

  • Was any of the answer helpful? Don’t forget to choose one and mark it so it can be used if someone has a similar question!

1 answer

0

It seems to me that the names of your columns are incorrect, but without the correct error message it is practically identifying the problem. So I rewrote your code in a slightly more readable way and with an error handling that will show on console what was the problem caused:

const express = require('express');
const sql = require('mssql');
const bodyParser = require('body-parser');

const app = express();
// Cria o pool de conexões do banco
const pool = new sql.ConnectionPool({
  server: 'devsqlcl2',
  database: 'AgrM6',
  port: 1433,
  user: 'papercut',
  password: 'Portage.2018',
}).connect();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post('/', async ({ body }, res) => {
  try {
    const resultado = await pool.request()
      .input('programm', 'Teste 1 2 3')
      .input('id', '39')
      .input('title', 'Finance')
      .query('INSERT INTO dbo.WIDS_API_TEST (programm, id, title) VALUES (@programm, @id, @title');

    console.log('Linhas afetadas', resultado.rowsAffected);

    res.send(resultado);
  } catch(e) {
    console.error(e);
    res.status(500).send('Erro interno');
  }
});

const server = app.listen(5000, () => {
  console.log('Server is running..');
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.