简体   繁体   English

将 nodejs 连接到 SQL Server

[英]Connecting nodejs to SQL Server

I am using this package with express-js and I have this connection settings but it returns an error:我正在将这个包与 express-js 一起使用,我有这个连接设置,但它返回一个错误:

TypeError: The "config.server" property is required and must be of type string.类型错误:“config.server”属性是必需的,并且必须是字符串类型。

Configuration:配置:

const config = new sql.ConnectionPool({
    user: 'USERNAME',
    password: 'PASSWORD',
    database: 'My_DATABASE_NAME',
    server: '120.000000.000,3306/SQLSERVER2014',
});

and then this code to execute procedure然后这段代码执行程序

app.get('/users', (req, res) => {
    sql.connect(config).then(pool =>{
        return pool.request()
        // .execute('procedure_name')
        .query('select * from AspNetUsers');
    }).then(result => {
        console.dir(result)
        pool.close();
    }).catch(err => {
        console.log(err);
        pool.close();
    });
});

Any idea what might be the issue with server value?知道server值可能有什么问题吗?

The lib document does not said like your example code. lib 文档不像您的示例代码那样说。 You push a ConnectionPool instance (stores in config variable) to connect function of sql .您推送一个ConnectionPool实例(存储在config变量中)以connect sql功能。

I think, you need choose one way to query data from mssql server:我认为,您需要选择一种从 mssql 服务器查询数据的方法:

  1. ConnectionPool , reuse your code, create a connection pool, then use it. ConnectionPool ,重用您的代码,创建一个连接池,然后使用它。
const pool = new sql.ConnectionPool({ // `pool` - clear variable name
  user: 'USERNAME',
  password: 'PASSWORD',
  database: 'My_DATABASE_NAME',
  server: 'localhost', // Example
});


//
app.get('/users', (req, res) => {
  pool.connect() // just call .connect
    .then(() => {
      return pool.request() // use `pool` const
        // .execute('procedure_name')
        .query('select * from AspNetUsers');
    }).then(result => {
      console.dir(result)
      pool.close();
    }).catch(err => {
      console.log(err);
      pool.close();
    });
});
  1. Create new connection pool for each time when you want to query data.每次要查询数据时都创建新的连接池。
const config = { // A "normal" json object
  user: 'USERNAME',
  password: 'PASSWORD',
  database: 'My_DATABASE_NAME',
  server: 'localhost', // Example
};


//
app.get('/users', (req, res) => {
  const pool = null;
  sql.connect(config) // create new connection pool
    .then(newPool => {
      pool = newPool;
      return pool.request()
        // .execute('procedure_name')
        .query('select * from AspNetUsers');
    }).then(result => {
      console.dir(result)
      pool.close();
    }).catch(err => {
      console.log(err);
      pool && pool.close();
    });
});

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

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