Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server connection to node js

I am trying to establish a connection between nodejs project and server running Microsoft SQL Server 2005. I am using a node module mssql, but I get these errors when I am attempting to create a connection:

{ [ConnectionError: Failed to connect to 123.123.12.1:1433 in 15000ms]
name: 'ConnectionError',
message: 'Failed to connect to 123.123.12.1:1433 in 15000ms',
code: 'ETIMEOUT' }

My connection being made by

var sql = require('mssql');

var dbConfig = {
    server:'123.123.12.1',
    database:'testingDB',
    user:'userName',
    password:'pass',
    port:1433
};

function getEmp() {
    var conn = new sql.Connection(dbConfig);
    var req = new sql.Request(conn);

    conn.connect(function(err) {
        if(err) {
            console.log(err);
            return;
        }
    else {
        console.log('success');
    }
});
}

getEmp();

I am not sure what I am doing wrong, I am using a cloud 9 IDE if that helps.

like image 247
crod Avatar asked Jan 05 '17 04:01

crod


People also ask

CAN node JS connect to SQL Server?

You can connect to a SQL Database using Node. js on Windows, Linux, or macOS.

How do I run a SQL query in node JS?

Step 1, install the NPM package called sqlite3 (Read the sqlite3 docs here). sqlite3 helps you to connect to your SQLite database and to run queries. Step 2, In your the JS file where you want to run the SQLs, import/require sqlite3 and fs (No, you don't need to install this one. It comes with NodeJS).

Is SQL good for node JS?

Node. js typically supports all database types, regardless of whether they're SQL or NoSQL. Nevertheless, the choice of a database must be made based on the complexity and purposes of your application.


1 Answers

Put your var req = new sql.Request(conn) inside connect.

// config for your database
var config = {
    user: 'sa',
    password: 'mypassword',
    server: 'localhost', 
    database: 'SchoolDB' 
};

// connect to your database
sql.connect(config, 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 Student', function (err, recordset) {

        if (err) console.log(err)

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

    });
});
like image 171
Saroj Avatar answered Sep 29 '22 05:09

Saroj