从nodeJS连接到SQL Server的问题

时间:2019-12-19 17:36:15

标签: node.js sql-server

所以我的问题是,该程序显然无法正常工作,但也没有崩溃。就像它永远不会执行try或catch一样。

const express = require("express"),
app = express(),
sql = require("mssql"),
port = 5000 || process.env.PORT,
bodyParser = require("body-parser"),
routerBoi = express.Router();

const sqlConfig = {
  user: "sa",
  password: "@Strongman105",
  server: "DESKTOP-RVS5F2QHSTESTSERVER",
  database: "master"
};

async () => {
  try {
    // make sure that any items are correctly URL encoded in the connection string
    await sql.connect(sqlConfig);
    const result = await sql.query(`select * from Users`);
    console.log(result);
  } catch (err) {
    console.log(err);
  }
};

// console.log that your server is up and running
app.listen(port, () => console.log(`Listening on port ${port}`));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

我的整个输出是“在端口5000上监听”。

我在这里做什么错了?

1 个答案:

答案 0 :(得分:1)

(async function() {
  try {
    await sql.connect(sqlConfig);
    const result = await sql.query(`select * from Users`);
    console.log(result);
  } catch (err) {
    console.log(err);
  }
})();

只需将您的异步函数用大括号括起来,然后使其成为自执行函数即可。您可以在官方文档中参考。 https://www.npmjs.com/package/mssql#asyncawait