使用Node.js连接到SQL Server数据库

fdbelqdn  于 2022-09-18  发布在  Java
关注(0)|答案(1)|浏览(416)

我想创建一个网站,可以访问一个数据库,在那里你基本上可以更新,插入和删除。我有最新版本的SQL Server,我计划使用node.js将我的数据库连接到我的前端,因为我预计会有很多流量,而noe.js很适合处理它。我正在阅读一些文档,我发现在处理高流量时,流媒体是最好的方法。

这是我的数据库

CREATE TABLE [dbo].[Users](
    [id] [int] IDENTITY(101,1) NOT NULL,
    [user_name] [nchar](255) NOT NULL,
    [user_lname] [nchar](255) NOT NULL,
    [user_username] [nchar](255) NOT NULL,
    [user_email] [nchar](255) NOT NULL,
    [user_phonenumber] [nchar](50) NOT NULL,
    [user_location] [nvarchar](255) NOT NULL,
    [subscription_type] [nvarchar](100) NULL,
    [sub_duration_in_months] [int] NULL,
    [subscription_date] [datetime] NULL,
    [subscription_deadline] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[Clients](
    [id] [int] IDENTITY(101,1) NOT NULL,
    [c_account_username] [nchar](255) NULL,
    [c_account_password] [nvarchar](255) NULL,
    [Client_or_Brand_name] [nvarchar](255) NOT NULL,
    [branch_location] [nchar](255) NOT NULL,
    [business_email] [nchar](255) NOT NULL,
    [business_phone] [nchar](100) NULL,
    [business_website] [nchar](255) NULL,
    [percentage_of_earnings] [float] NOT NULL,
    [number_of_affiliated_users] [int] NULL,
    [total_earnings_via_users] [numeric](18, 2) NULL,
    [total_earnings_via_users_this_month] [numeric](18, 2) NULL,
PRIMARY KEY CLUSTERED 

CREATE TABLE [dbo].[transactions](
    [id] [int] IDENTITY(101,1) NOT NULL,
    [user_id] [int] NOT NULL,
    [client_id] [int] NOT NULL,
    [time_of_transaction] [datetime] NULL,
    [receit_id] [nvarchar](255) NULL,
    [receit_total] [nchar](10) NULL
) ON [PRIMARY]
GO

以下是该脚本的代码:

const sql = require('mssql')

const config = {
    user: 'DESKTOP-9JKA425\user',
    password: '',
    server: 'localhost\DESKTOP-9JKA425', // You can use 'localhost\instance' to connect to named instance
    database: 'PD',
}

sql.connect(config, err => {

    console.log(err)
    // ... error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from Users') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // ... error handler
})

现在,当我运行这段代码时,我得到以下错误:

ConnectionError: Failed to connect to localhostDESKTOP-9JKA425 in 15000ms
    at C:UsersuserDesktopnewnewnode_modulesmssqllibtediousconnection-pool.js:70:17
    at Connection.onConnect (C:UsersuserDesktopnewnewnode_modulestediouslibconnection.js:1020:9)
    at Object.onceWrapper (node:events:628:26)
    at Connection.emit (node:events:513:28)
    at Connection.emit 
(C:UsersuserDesktopnewnewnode_modulestediouslibconnection.js:1048:18)
    at Connection.connectTimeout 
(C:UsersuserDesktopnewnewnode_modulestediouslibconnection.js:1258:10)
    at Timeout._onTimeout 
(C:UsersuserDesktopnewnewnode_modulestediouslibconnection.js:1203:12)
    at listOnTimeout (node:internal/timers:559:17)
    at processTimers (node:internal/timers:502:7) {
  code: 'ETIMEOUT',
  originalError: ConnectionError: Failed to connect to localhostDESKTOP-9JKA425 in 15000ms
      at Connection.connectTimeout 
(C:UsersuserDesktopnewnewnode_modulestediouslibconnection.js:1258:26)
      at Timeout._onTimeout 
(C:UsersuserDesktopnewnewnode_modulestediouslibconnection.js:1203:12)
      at listOnTimeout (node:internal/timers:559:17)
      at processTimers (node:internal/timers:502:7) {
    code: 'ETIMEOUT',
    isTransient: undefined
  }
}

我可以断定,这可能是因为我的连接,要么是我的服务器不正确,要么是类似的东西。

任何帮助都将不胜感激。

pu3pd22g

pu3pd22g1#

var express = require('express');
var app = express();
var sql = require("mssql");

const  config = {
  user:  'foo', // sql user
  password:  'foo', //sql user password
  server:  '127.0.0.1', // if it does not work try- localhost
  database:  'Products',
  options: {
    trustedconnection:  true,
    enableArithAbort:  true,
    instancename:  'SQLEXPRESS'  // SQL Server instance name
  },
  port:  55892
}

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);

 });
});

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

相关问题