简体   繁体   English

为什么我无法使用 NodeJS 连接到 SQLServer?

[英]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.我是使用 Node JS 的新手,现在我正在创建一个连接到 SQL Server 的项目,但是当我使用命令node Database\\connect.js它什么也不做,因为它应该执行它所做的 console.log连接或没有。

Here is my package.json这是我的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这是我的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. connection.on(...)方法不会启动数据库连接本身。 It only runs when the application initiates it using connection.connect() method.它仅在应用程序使用connection.connect()方法启动它时运行。

Since you are exporting connection to the outside from connect.js , You should import and initiate the connection somewhere (mostly in application entry point) ,由于您是从connect.js向外部导出connection ,因此您应该在某处(主要在应用程序入口点)导入并启动连接,

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

// initiate
connection.connect();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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