简体   繁体   English

如何将现有的 nodejs 服务器应用程序连接到 Azure SQL 数据库

[英]How to connect an existing nodejs server app to Azure SQL database

Can anyone please advise:任何人都可以请建议:

I have an existing nodejs server running on azure, running node 10.14 on Linux.我有一个在 azure 上运行的现有 nodejs 服务器,在 Linux 上运行节点 10.14。 The project code is on github and when I push changes they are automatically pushed to azure.项目代码在 github 上,当我推送更改时,它们会自动推送到 azure。

I have set up a database server and database though the Azure portal and can query it through the Azure portal.我已经通过 Azure 门户设置了数据库服务器和数据库,并且可以通过 Azure 门户进行查询。

I want to modify the nodejs server to conect to the database, I have the connection string code etc. but just the act of adding the line:我想修改 nodejs 服务器以连接到数据库,我有连接字符串代码等,但只是添加行的行为:

var mysql = require('mysql'); 

will stop the server form running as presumably I have not installed mysql on the machine which is running the server in the Azure cloud.将停止服务器表单运行,因为我可能没有在 Azure 云中运行服务器的机器上安装 mysql。

How can I get this to work?我怎样才能让它工作?

Thanks for any help, Mitch.谢谢你的帮助,米奇。

According to the error, you do not add the package in your package.json file and install the package in your project. According to the error, you do not add the package in your package.json file and install the package in your project. Besides, if you want to connect Azure SQL server database, we can use package mssqql另外,如果要连接Azure SQL服务器数据库,我们可以使用package mssqql

For example例如

  1. My package.json file我的package.json文件
{
....
  
    "dependencies": {
        "express": "^4.17.1",
        "mssql": "^6.2.0",
        "request": "^2.88.2"
    }

}
  1. code代码
const router = express.Router()
const sql = require('mssql')


const config = {

  user: "<user name>",
  password: "<password>",
  server: "<your SQL server name>.database.windows.net",
  port: 1433,
  database: "test",
  connectionTimeout: 3000,
  parseJSON: true,
  options: {
    encrypt: true,
    enableArithAbort: true
  },
  pool: {
    min: 0,
    idleTimeoutMillis: 3000
  }
};
const pool = new sql.ConnectionPool(config);
const poolConnect = pool.connect();

router.get('/', async function (req, res) {
  
  await poolConnect;
  try {
    const request = pool.request(); 
    const result = await request.query('select 1 as number')
    console.log(result);
    res.json(result.recordset);
    
} catch (err) {
    console.error('SQL error', err);
    res.send(err);
}
});
  1. Test.测试。

在此处输入图像描述

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

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