简体   繁体   中英

Why can't I connect to SQLServer uisng NodeJS?

I'm new using Node JS and now I'm creating a project that connects to SQL Server, but when I use the command node Database\\connect.js It simply does do nothing, as it should do a console.log that it did connect or it didn't.

Here is my package.json

{
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "tedious": "^14.0.0"
  },
  "name": "weather-nodejs-apirest",
  "version": "1.0.0",
  "main": "connect.js",
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "description": ""
}

And here is my connect.js

var Connection = require('tedious').Connection;
var config = {
    server: 'SERVERNAME',
    authentication: {
        type: 'default',
        options: {
            userName: 'sa',
            password: 'password'
        }
    },
    options: {
        database: 'weather_app',
        // instanceName: 'Sqlexpress',
        rowCollectionOnDone: true,
        useColumnNames: false
    }
}

var connection = new Connection(config);
connection.on('connect', function (err) {
    if (err) {
        console.log(err);
    } else {
        console.log('Connected');
    }
});

module.exports = connection;

The connection.on(...) method will not initiate the database connection itself. It only runs when the application initiates it using connection.connect() method.

Since you are exporting connection to the outside from connect.js , You should import and initiate the connection somewhere (mostly in application entry point) ,

const connection = require('path/to/connect.js');

// initiate
connection.connect();

Doc: http://tediousjs.github.io/tedious/getting-started.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM