创建数据库后连接到SQL Server数据库

时间:2018-12-06 10:28:27

标签: node.js sql-server node-mssql

我正在通过Node.js连接到Azure托管的SQL Server数据库。 我的代码如下:

const database = 'test';
const options = {
  user: 'user',
  password: 'password',
  server: '<server>.database.windows.net',
  encrypt: true
};

const pool1 = new ConnectionPool(options);
try {
  await pool1.connect();
  const request = pool1.request();
  await request.query(`CREATE DATABASE "${database}"`);
}
catch (err) {
  console.error(err);
}
finally {
  await pool1.close();
}

options.database = database;
const pool2 = new ConnectionPool(options);
try {
  await pool2.connect();
}
catch (err) {
  console.error(err);
}
finally {
  await pool2.close();
}

数据库test已成功创建,但是直接通过pool2.connect()连接到数据库时,会引发错误:

An error occured: Login failed for user 'user'.
ConnectionError: Login failed for user 'user'.
    at Connection.tedious.once.err ([dir]/node_modules/mssql/lib/tedious.js:239:17)
    at Object.onceWrapper (events.js:273:13)
    at Connection.emit (events.js:182:13)
    at Connection.processLogin7Response ([dir]/node_modules/tedious/lib/connection.js:1314:16)
    at Connection.message ([dir]/node_modules/tedious/lib/connection.js:1827:14)
    at Connection.dispatchEvent ([dir]/node_modules/tedious/lib/connection.js:1012:38)
    at MessageIO.<anonymous> ([dir]/node_modules/tedious/lib/connection.js:891:18)
    at MessageIO.emit (events.js:182:13)
    at Message.<anonymous> ([dir]/node_modules/tedious/lib/message-io.js:60:15)
    at Message.emit (events.js:187:15)

现在,如果我再次运行相同的代码,它不会再次引发错误,因此我猜测是因为我尝试在创建数据库后立即连接到数据库。我还尝试使用pool2.query('USE database')而不是将database传递给池选项,但是又遇到另一个错误,提示我在创建数据库后无法使用USE

我正在使用mssql4.2.3node10.1.0

0 个答案:

没有答案