NodeJS using mssql to connect to SQLServer appears "Incorrect syntax near the keyword \ 'user \'."

"Incorrect syntax near the keyword 'user'." Error occurred recently when using the mssql module of NodeJS to connect to the SQLServer database. Google found that I used user as an indicator in SQLServer, but user in SQLServer is a reserved keyword. Cannot be used as a table name or variable name. So the solution is very simple, just rename the table name user to t_user or another name.

Define the table structure user in SQLServer and add data to it

I am using Windows 10 system, SQLServer2012 database is installed in the local system, you can use SQL Server Management Studio or Navicat Premium 12 and other tools to connect to SQLServer database. I used to use this database Navicat Premium 12 client tool to connect to SQLServer database, created in Navicat Premium 12 in UserDB database, then create a user table
, its table structure is defined as follows:
user table structure
add a few tables for the user A record, as shown below:
Data in user table
The SQL script of the corresponding user table is as follows:

/*
Navicat Premium Data Transfer

Source Server         : localhost_SqlServer
Source Server Type    : SQL Server
Source Server Version : 11002100
Source Host           : localhost:1433
Source Catalog        : UserDB
Source Schema         : dbo

Target Server Type    : SQL Server
Target Server Version : 11002100
File Encoding         : 65001

Date: 06/03/2020 07:50:41
*/


-- ----------------------------
-- Table structure for user
-- ----------------------------
IF EXISTS (SELECT * FROM sys.all_objects WHERE object_id = OBJECT_ID(N'[dbo].[user]') AND type IN ('U'))
   DROP TABLE [dbo].[user]
GO

CREATE TABLE [dbo].[user] (
 [name] varchar(255) COLLATE Chinese_PRC_CI_AS  NULL,
 [age] int  NULL,
 [sex] tinyint  NULL
)
GO

ALTER TABLE [dbo].[user] SET (LOCK_ESCALATION = TABLE)
GO


-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO [dbo].[user]  VALUES (N'小明', N'23', N'1')
GO

INSERT INTO [dbo].[user]  VALUES (N'王五', N'21', N'1')
GO

INSERT INTO [dbo].[user]  VALUES (N'小红', N'20', N'0')
GO

INSERT INTO [dbo].[user]  VALUES (N'小丽', N'22', N'0')
GO

Configure the NodeJS environment, install Node and NPM, VSCode and other IDEs in advance, and then install the mssql module in the terminal under the VSCode project directory

The mssql module is an npm module for connecting to the SQLServer database under NodeJS. Its npm address is: https://www.npmjs.com/package/mssql The
installation command is as follows:

npm install mssql

Use mssql to connect to SQLServer in NodeJS and query the user table in UserDB database

Create a mssqlTest.js file in the corresponding directory in VSCode, the code is as follows:

// mssql模块的简单使用
// https://www.npmjs.com/package/mssql
var sql = require('mssql');

// DB configuration
var dbConfig = {
 user: 'sa',
 password: '1030',
 server: 'localhost',
 database: 'UserDB',
 port: 1433,
 pool: {
     max: 10,
     min: 0,
     idleTimeoutMillis: 30000
 }
};

// 查询所有的用户信息
function getAllUsers() {
 var conn = new sql.ConnectionPool(dbConfig);
 //console.log(conn);
 var req = new sql.Request(conn);
 conn.connect(function (err) {
     if (err) {
         console.log(err);
         return;
     }
     // 查询user表
     req.query("SELECT * FROM user", function (err, recordset) {
         if (err) {
             console.log(err);
             return;
         }
         else {
             console.log(recordset);
         }
         conn.close();
     });
 });
 }
 
// 查询所有的用户信息
getAllUsers();

The above code mainly uses the mssql module to connect to the SQLServer database. First, set up the connection pool information of the SQLServer database, and then query the user table, and print the results after the query. Running in VSCode did not expect the following error to occur. Show: The
Error screenshot
error message "Incorrect syntax near the keyword 'user'.", So Gogole search found that many people also have this problem:
Error message
In the blog garden [Incorrect syntax near the keyword 'user'. Solution] (Incorrect syntax near The keyword 'user'. Solution) found this blog
post by blogger Langji Tianya, the reason is: in postgresql, sql99 and sql92 all use user as a reserved word! Since it is a reserved word, it cannot be used.
The solution is to change the table name user to t_user or another name. This error is described in detail
in the c # incorrect syntax near the keyword 'user' question at https://stackoverflow.com :

Microsoft SQL Server uses reserved keywords for defining, manipulating, and accessing databases. Reserved keywords are part of the grammar of the Transact-SQL language that is used by SQL Server to parse and understand Transact-SQL statements and batches. Although it is syntactically possible to use SQL Server reserved keywords as identifiers and object names in Transact-SQL scripts, you can do this only by using delimited identifiers.
Available from https://docs.microsoft.com/en-us/sql/t-sql/language -elements / reserved-keywords-transact-sql? view = sql-server-2017See the list of reserved words in the SQLServer database, as shown in the following figure:
figure 1
figure 2
From the above figure 2, you can see that USER is a reserved word in the SQLServer database , Users cannot use it as an indicator.

Change the table name user to t_user in the SQLServer database UserDB, and then modify the table name in the mssqlTest.js code

The modified mssqlTest.js code is as follows:

// mssql模块的简单使用
// https://www.npmjs.com/package/mssql
var sql = require('mssql');

// DB configuration
var dbConfig = {
  user: 'sa',
  password: '1030',
  server: 'localhost',
  database: 'UserDB',
  port: 1433,
  pool: {
      max: 10,
      min: 0,
      idleTimeoutMillis: 30000
  }
};

// 查询所有的用户信息
function getAllUsers() {
  var conn = new sql.ConnectionPool(dbConfig);
  //console.log(conn);
  var req = new sql.Request(conn);
  conn.connect(function (err) {
      if (err) {
          console.log(err);
          return;
      }
      // 查询t_user表
      req.query("SELECT * FROM t_user", function (err, recordset) {
          if (err) {
              console.log(err);
              return;
          }
          else {
              console.log(recordset);
          }
          conn.close();
      });
  });
  }
  
// 查询所有的用户信息
getAllUsers();

The screenshot of running in VSCode is shown below:
operation result

References

Published 131 original articles · Like 38 · Visit 990,000+

Guess you like

Origin blog.csdn.net/ccf19881030/article/details/104688626