Giao dịch nhóm kết nối mysql của nodejs

Giả sử bạn đã đặt các biến môi trường phù hợp, bạn có thể xây dựng một đối tượng cấu hình như sau

Show

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}

Tài liệu

ví dụ

Cấu hình

trình điều khiển

kết nối

yêu cầu

giao dịch

báo cáo chuẩn bị

Khác

ví dụ

cấu hình

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}

Không đồng bộ/Đang chờ

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})

lời hứa

Truy vấn

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});

thủ tục lưu trữ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

Lời hứa bản địa được sử dụng theo mặc định. Bạn có thể dễ dàng thay đổi điều này với

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})
9

Văn bản mẫu được gắn thẻ ES6

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})

Tất cả các giá trị được tự động khử trùng bằng cách tiêm sql. Điều này là do nó được hiển thị dưới dạng câu lệnh đã chuẩn bị và do đó, tất cả các giới hạn áp dụng trong MS SQL đối với các tham số đều được áp dụng. e. g. Không thể chuyển/đặt tên cột trong câu lệnh sử dụng biến

gọi lại

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})

truyền trực tuyến

Nếu bạn dự định làm việc với số lượng hàng lớn, bạn nên luôn sử dụng phát trực tuyến. Khi bạn bật tính năng này, bạn phải lắng nghe các sự kiện để nhận dữ liệu

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})

Khi truyền phát các tập dữ liệu lớn, bạn muốn sao lưu hoặc chia nhỏ lượng dữ liệu bạn đang xử lý để tránh các sự cố cạn kiệt bộ nhớ; . Dưới đây là một ví dụ về quản lý các hàng theo lô 15

let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}

Nhóm kết nối

Một khái niệm quan trọng cần hiểu khi sử dụng thư viện này là Tổng hợp kết nối vì thư viện này sử dụng rộng rãi tổng hợp kết nối. Vì một quy trình Node JS có thể xử lý nhiều yêu cầu cùng một lúc, nên chúng ta có thể tận dụng quy trình chạy dài này để tạo nhóm kết nối cơ sở dữ liệu để tái sử dụng;

Với những lợi thế của việc gộp chung đi kèm với một số phức tạp bổ sung, nhưng những điều này hầu hết chỉ là khái niệm và một khi bạn hiểu cách thức hoạt động của việc gộp này, thật đơn giản để sử dụng nó một cách hiệu quả và hiệu quả

Nhóm kết nối toàn cầu

Để hỗ trợ quản lý nhóm trong ứng dụng của bạn, có chức năng

let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
1 được sử dụng để kết nối với nhóm kết nối toàn cầu. Bạn có thể thực hiện các cuộc gọi lặp lại đến chức năng này và nếu nhóm chung đã được kết nối, nó sẽ phân giải thành nhóm được kết nối. Ví dụ sau lấy nhóm kết nối toàn cầu bằng cách chạy
let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
1, sau đó chạy truy vấn đối với nhóm

NB. Điều quan trọng cần lưu ý là chỉ có thể có một nhóm kết nối toàn cầu được kết nối tại một thời điểm. Cung cấp cấu hình kết nối khác cho chức năng

let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
3 sẽ không tạo kết nối mới nếu nó đã được kết nối

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
0

Chờ đợi hoặc

let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
4-ing việc tạo nhóm là một cách an toàn để đảm bảo rằng nhóm luôn sẵn sàng mà không cần biết nó cần ở đâu trước. Trong thực tế, một khi nhóm được tạo thì sẽ không có độ trễ cho cuộc gọi
let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
3 tiếp theo

Cũng xin lưu ý rằng chúng tôi không đóng nhóm toàn cầu bằng cách gọi

let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
6 sau khi truy vấn được thực thi, bởi vì các truy vấn khác có thể cần được chạy đối với nhóm này và việc đóng nó sẽ thêm chi phí bổ sung để chạy các truy vấn tiếp theo. Bạn chỉ nên đóng nhóm toàn cầu nếu bạn chắc chắn rằng ứng dụng đã hoàn tất. Hoặc ví dụ: nếu bạn đang chạy một số loại công cụ CLI hoặc công việc CRON, bạn có thể đóng nhóm ở cuối tập lệnh

Phiên bản đơn nhóm chung toàn cầu

Khả năng gọi

let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
3 và
let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
8 nhiều lần trên nhóm toàn cầu nhằm mục đích giúp việc quản lý nhóm dễ dàng hơn, tuy nhiên, tốt hơn là bạn nên duy trì tham chiếu của riêng mình tới nhóm, trong đó
let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
3 được gọi một lần và kết quả là lời hứa kết nối của nhóm toàn cầu được sử dụng lại

Ví dụ: trong các ứng dụng Express, cách tiếp cận sau đây sử dụng một phiên bản nhóm toàn cầu duy nhất được thêm vào

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
00 để ứng dụng có quyền truy cập vào nó khi cần. Khởi động máy chủ sau đó được xâu chuỗi bên trong lời hứa
let rowsToProcess = [];
request.on('row', row => {
  rowsToProcess.push(row);
  if (rowsToProcess.length >= 15) {
    request.pause();
    processRows();
  }
});
request.on('done', () => {
    processRows();
});

function processRows() {
  // process rows
  rowsToProcess = [];
  request.resume();
}
3

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
1

Sau đó, tuyến đường sử dụng nhóm kết nối trong đối tượng

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
00

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
2

Quản lý hồ bơi nâng cao

Đối với một số trường hợp sử dụng, bạn có thể muốn triển khai quản lý nhóm kết nối của riêng mình, thay vì sử dụng nhóm kết nối toàn cầu. Lý do để làm điều này bao gồm

  • Hỗ trợ kết nối tới nhiều cơ sở dữ liệu
  • Tạo các nhóm riêng biệt cho các hoạt động đọc và đọc/ghi

Đoạn mã sau là một ví dụ về triển khai nhóm kết nối tùy chỉnh

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
3

Tệp này sau đó có thể được sử dụng trong ứng dụng của bạn để tạo, tìm nạp và đóng nhóm

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
4

Tương tự như nhóm kết nối toàn cầu, bạn nên đặt mục tiêu chỉ đóng một nhóm khi bạn biết ứng dụng sẽ không bao giờ cần đến nó nữa. Thông thường, điều này sẽ chỉ xảy ra khi ứng dụng của bạn đang tắt

Thao tác giá trị kết quả

Trong một số trường hợp, mong muốn thao tác dữ liệu bản ghi khi nó được trả về từ cơ sở dữ liệu, điều này có thể là chuyển nó thành một đối tượng cụ thể (ví dụ:. đối tượng

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
03 thay vì
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
04) hoặc tương tự

Trong v8. 0. 0+ có thể đăng ký trình xử lý theo kiểu dữ liệu

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
5

Cấu hình

Sau đây là một đối tượng cấu hình ví dụ

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
6

Chung (giống nhau cho tất cả các trình điều khiển)

  • người dùng - Tên người dùng để sử dụng để xác thực
  • mật khẩu - Mật khẩu để sử dụng để xác thực
  • máy chủ - Máy chủ để kết nối với. Bạn có thể sử dụng ‘localhost\instance’ để kết nối với phiên bản được đặt tên
  • cổng - Cổng để kết nối (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    05). Không đặt khi kết nối với phiên bản được đặt tên
  • tên miền - Sau khi bạn đặt tên miền, trình điều khiển sẽ kết nối với SQL Server bằng thông tin đăng nhập tên miền
  • cơ sở dữ liệu - Cơ sở dữ liệu để kết nối với (mặc định. phụ thuộc vào cấu hình máy chủ)
  • connectionTimeout - Thời gian chờ kết nối tính bằng ms (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    06)
  • requestTimeout - Thời gian chờ yêu cầu tính bằng ms (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    06). GHI CHÚ. trình điều khiển msnodesqlv8 không hỗ trợ thời gian chờ < 1 giây. Khi được truyền qua chuỗi kết nối, khóa phải là
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    08
  • luồng - Truyền bản ghi/hàng thay vì trả lại tất cả chúng cùng một lúc dưới dạng đối số gọi lại (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    09). Bạn cũng có thể bật phát trực tuyến cho từng yêu cầu một cách độc lập (______010). Luôn đặt thành
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    11 nếu bạn định làm việc với số lượng hàng lớn
  • parseJSON - Phân tích bộ bản ghi JSON thành các đối tượng JS (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    09). Để biết thêm thông tin, vui lòng xem phần Hỗ trợ JSON
  • hồ bơi. max - Số lượng kết nối tối đa có thể có trong nhóm (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    13)
  • hồ bơi. tối thiểu - Số kết nối tối thiểu có thể có trong nhóm (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    14)
  • hồ bơi. idleTimeoutMillis - Số mili giây trước khi đóng kết nối không sử dụng (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    15)
  • arrayRowMode - Trả về kết quả hàng dưới dạng một mảng thay vì đối tượng có khóa. Cũng thêm mảng
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    16. (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    09) Xem Xử lý tên cột trùng lặp

Danh sách đầy đủ các tùy chọn nhóm có thể được tìm thấy ở đây

định dạng

Ngoài đối tượng cấu hình, còn có một tùy chọn để chuyển cấu hình dưới dạng chuỗi kết nối. Chuỗi kết nối được hỗ trợ

Chuỗi kết nối cổ điển

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
7

trình điều khiển

tẻ nhạt

Trình điều khiển mặc định, được bảo trì tích cực và sẵn sàng sản xuất. Nền tảng độc lập, chạy ở mọi nơi Node. js chạy. Chính thức được hỗ trợ bởi Microsoft

tùy chọn bổ sung

  • beforeConnect(conn) - Chức năng, được gọi trước khi mở kết nối. Tham số
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    18 là cấu hình phía sau
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    19. Nó có thể được sử dụng để đính kèm các trình xử lý sự kiện như trong ví dụ này

    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    8

  • tùy chọn. instanceName - Tên phiên bản để kết nối với. Dịch vụ Trình duyệt máy chủ SQL phải đang chạy trên máy chủ cơ sở dữ liệu và cổng UDP 1434 trên máy chủ cơ sở dữ liệu phải có thể truy cập được
  • tùy chọn. useUTC - Một boolean xác định có hay không sử dụng thời gian UTC cho các giá trị không có chênh lệch múi giờ (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    11)
  • tùy chọn. mã hóa - Một boolean xác định xem kết nối có được mã hóa hay không (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    11)
  • tùy chọn. tdsVersion - Phiên bản TDS sẽ sử dụng (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    22, có sẵn. ________ 023, ________ 024, ________ 025, ________ 026, ________ 022)
  • tùy chọn. appName - Tên ứng dụng được sử dụng để ghi nhật ký máy chủ SQL
  • tùy chọn. abortTransactionOnError - Một boolean xác định có tự động khôi phục giao dịch hay không nếu gặp phải bất kỳ lỗi nào trong quá trình thực hiện giao dịch đã cho. Điều này đặt giá trị cho
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    28 trong giai đoạn SQL ban đầu của kết nối

xác thực

Ngoài các tùy chọn bổ sung, có thể thêm thuộc tính

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
29 vào tùy chọn cấu hình nhóm

  • xác thực - Một đối tượng có cài đặt xác thực, theo Tài liệu Tedious. Vượt qua đối tượng này sẽ ghi đè cài đặt
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    30,
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    31,
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    32
  • xác thực. loại - Loại phương pháp xác thực, loại hợp lệ là
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    33,
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    34,
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    35,
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    36,
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    37, hoặc
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    38
  • xác thực. tùy chọn - Tùy chọn xác thực được yêu cầu bởi trình điều khiển
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    39, phụ thuộc vào
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    40. Để biết thêm chi tiết, hãy kiểm tra Giao diện xác thực Tedious

Thông tin thêm về các tùy chọn cụ thể Tedious. http. // tẻ nhạt. github. io/tẻ nhạt/kết nối api. html

Trình điều khiển Microsoft / Contributor Node V8 cho Node. js cho máy chủ SQL

Yêu cầu nút. js v10+ trở lên. Chỉ dành cho Windows 32-64 bit hoặc Linux/macOS 64 bit. Trình điều khiển này không phải là một phần của gói mặc định và phải được cài đặt riêng trước

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
41. Để sử dụng trình điều khiển này, hãy sử dụng cú pháp yêu cầu này.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
42

Ghi chú. Nếu bạn sử dụng nhập vào lib của mình để chuẩn bị yêu cầu của mình (

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
43), bạn cũng cần nâng cấp tất cả các loại nhập vào mã của mình (
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
44) nếu không sẽ xảy ra lỗi
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
45

tùy chọn bổ sung

  • beforeConnect(conn) - Chức năng, được gọi trước khi mở kết nối. Tham số
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    18 là cấu hình kết nối, có thể được sửa đổi để chuyển các tham số bổ sung cho phương thức
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    47 của trình điều khiển
  • connectionString - Chuỗi kết nối (mặc định. xem bên dưới)
  • tùy chọn. instanceName - Tên phiên bản để kết nối với. Dịch vụ Trình duyệt máy chủ SQL phải đang chạy trên máy chủ cơ sở dữ liệu và cổng UDP 1444 trên máy chủ cơ sở dữ liệu phải có thể truy cập được
  • tùy chọn. kết nối đáng tin cậy - Sử dụng Xác thực Windows (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    09)
  • tùy chọn. useUTC - Một boolean xác định có hay không sử dụng thời gian UTC cho các giá trị không có chênh lệch múi giờ (mặc định.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    11)

Chuỗi kết nối mặc định khi kết nối với cổng

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
9

Chuỗi kết nối mặc định khi kết nối với phiên bản được đặt tên

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
0

Xin lưu ý rằng chuỗi kết nối với trình điều khiển này không giống nhau hơn là tẻ nhạt và sử dụng yes/no thay vì true/false. Bạn có thể xem thêm trên tài liệu ODBC

kết nối

Trong nội bộ, mỗi phiên bản

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
50 là một nhóm kết nối TDS riêng biệt. Sau khi bạn tạo một
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
51/
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
52/
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
53 mới, một kết nối TDS mới sẽ được lấy từ nhóm và dành riêng cho hành động mong muốn. Khi hành động hoàn tất, kết nối sẽ được giải phóng trở lại nhóm. Kiểm tra tình trạng kết nối được tích hợp sẵn nên khi phát hiện ra kết nối chết, nó sẽ ngay lập tức được thay thế bằng một kết nối mới

QUAN TRỌNG. Luôn đính kèm trình nghe

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
54 vào kết nối đã tạo. Bất cứ khi nào có sự cố với kết nối, nó sẽ phát ra lỗi và nếu không có người nghe, nó sẽ làm hỏng ứng dụng của bạn với một lỗi chưa được phát hiện

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
1

Sự kiện

  • lỗi (err) - Gửi đi do lỗi kết nối

kết nối ([gọi lại])

Tạo nhóm kết nối mới. Kết nối thăm dò ban đầu được tạo để tìm hiểu xem cấu hình có hợp lệ hay không

Tranh luận

  • gọi lại (err) - Một cuộc gọi lại được gọi sau khi kết nối đầu dò ban đầu được thiết lập hoặc đã xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
2

lỗi

  • ELOGIN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Đăng nhập thất bại
  • ETIMEOUT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Hết thời gian kết nối
  • EALREADYCONNECTED (_______055) - Cơ sở dữ liệu đã được kết nối
  • EALREADYCONNECTING (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Đã kết nối với cơ sở dữ liệu
  • EINSTLOOKUP (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Tra cứu phiên bản không thành công
  • ESOCKET (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Lỗi ổ cắm

gần()

Đóng tất cả các kết nối đang hoạt động trong nhóm

Thí dụ

Lời yêu cầu

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
3

Nếu bạn bỏ qua đối số nhóm/giao dịch, nhóm chung sẽ được sử dụng thay thế

Sự kiện

  • bộ bản ghi (cột) - Được gửi đi khi siêu dữ liệu cho bộ bản ghi mới được phân tích cú pháp
  • hàng(hàng) - Gửi đi khi hàng mới được phân tích cú pháp
  • done(returnValue) - Được gửi đi khi yêu cầu hoàn tất
  • error(err) - Gửi đi do lỗi
  • thông tin (tin nhắn) - Gửi đi trên tin nhắn thông tin

thực thi (thủ tục, [gọi lại])

Gọi một thủ tục được lưu trữ

Tranh luận

  • thủ tục - Tên của thủ tục được lưu trữ sẽ được thực thi
  • callback(err, recordsets, returnValue) - Một cuộc gọi lại được gọi sau khi quá trình thực thi hoàn tất hoặc đã xảy ra lỗi.
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    61 cũng có thể truy cập dưới dạng thuộc tính của bộ bản ghi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
4

lỗi

  • YÊU CẦU (______062) - Thông báo từ SQL Server
  • ECANCEL (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Đã hủy
  • ETIMEOUT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Yêu cầu hết thời gian chờ
  • ENOCONN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Không có kết nối nào được chỉ định cho yêu cầu đó
  • ENOTOPEN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Chưa mở kết nối
  • ECONNCLOSED (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Kết nối bị đóng
  • ENOTBEGUN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch chưa bắt đầu
  • EABORT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch bị hủy bỏ (do người dùng hoặc do lỗi)

đầu vào (tên, [loại], giá trị)

Thêm một tham số đầu vào vào yêu cầu

Tranh luận

  • tên - Tên của tham số đầu vào không có @ char
  • type - kiểu dữ liệu SQL của tham số đầu vào. Nếu bạn bỏ qua loại, mô-đun sẽ tự động quyết định loại dữ liệu SQL nào sẽ được sử dụng dựa trên loại dữ liệu JS
  • giá trị - Giá trị tham số đầu vào. Giá trị
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    70 và
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    71 được tự động chuyển đổi thành giá trị
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    72

Thí dụ

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
5

Kiểu dữ liệu JS sang Bản đồ kiểu dữ liệu SQL

  • const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    73 -> 
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    74
  • const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    75 ->
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    76
  • const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    77 ->
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    78
  • const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    04 ->
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    80
  • const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    81 ->
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    82
  • ________ 083 -> ________ 084

Kiểu dữ liệu mặc định cho đối tượng không xác định là

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
74

Bạn có thể xác định loại bản đồ của riêng bạn

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
6

Bạn cũng có thể ghi đè lên bản đồ loại mặc định

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
7

Lỗi (đồng bộ)

  • EARGS (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Số đối số không hợp lệ
  • EINJECT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Cảnh báo SQL injection

NB. Không sử dụng các tham số

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
88 vì chúng được sử dụng bởi các trình điều khiển bên trong và gây ra xung đột

đầu ra (tên, loại, [giá trị])

Thêm một tham số đầu ra vào yêu cầu

Tranh luận

  • tên - Tên của tham số đầu ra không có @ char
  • type - kiểu dữ liệu SQL của tham số đầu ra
  • giá trị - Giá trị tham số đầu ra giá trị ban đầu. Giá trị
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    70 và
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    71 được tự động chuyển đổi thành giá trị
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    72. Không bắt buộc

Thí dụ

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
8

Lỗi (đồng bộ)

  • EARGS (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Số đối số không hợp lệ
  • EINJECT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Cảnh báo SQL injection

toReadableStream

Chuyển đổi yêu cầu thành một Nút. js ReadableStream

Thí dụ

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
9

HOẶC nếu bạn muốn tăng highWaterMark của luồng đã đọc để đệm nhiều hàng hơn trong bộ nhớ

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
0

ống (dòng)

Đặt yêu cầu thành chế độ

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
94 và kéo tất cả các hàng từ tất cả các tập bản ghi vào một luồng nhất định

Tranh luận

  • luồng - Luồng có thể ghi ở chế độ đối tượng

Thí dụ

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
1


truy vấn (lệnh, [gọi lại])

Thực hiện lệnh SQL. Để thực thi các lệnh như

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
95 hoặc nếu bạn dự định làm việc với các bảng tạm thời cục bộ, hãy sử dụng lô thay thế

Tranh luận

  • lệnh - Lệnh T-SQL sẽ được thực thi
  • gọi lại (err, recordset) - Một cuộc gọi lại được gọi sau khi thực hiện xong hoặc xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
2

lỗi

  • ETIMEOUT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Yêu cầu hết thời gian chờ
  • YÊU CẦU (______062) - Thông báo từ SQL Server
  • ECANCEL (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Đã hủy
  • ENOCONN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Không có kết nối nào được chỉ định cho yêu cầu đó
  • ENOTOPEN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Chưa mở kết nối
  • ECONNCLOSED (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Kết nối bị đóng
  • ENOTBEGUN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch chưa bắt đầu
  • EABORT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch bị hủy bỏ (do người dùng hoặc do lỗi)

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
3

GHI CHÚ. Để biết số hàng bị ảnh hưởng bởi (các) câu lệnh, hãy xem phần Hàng bị ảnh hưởng


lô (đợt, [gọi lại])

Thực hiện lệnh SQL. Không giống như truy vấn, nó không sử dụng

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
04, do đó, không có khả năng SQL Server sẽ sử dụng lại kế hoạch thực thi mà nó tạo ra cho SQL. Chỉ sử dụng điều này trong những trường hợp đặc biệt, chẳng hạn như khi bạn cần thực thi các lệnh như
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
95 không thể thực hiện được bằng truy vấn hoặc nếu bạn đang thực thi các câu lệnh dài hơn 4000 ký tự trên SQL Server 2000. Ngoài ra, bạn nên sử dụng điều này nếu bạn dự định làm việc với các bảng tạm thời cục bộ (thông tin thêm tại đây)

GHI CHÚ. Thông số có giá trị theo bảng (TVP) không được hỗ trợ theo đợt

Tranh luận

  • lô - Lệnh T-SQL sẽ được thực thi
  • gọi lại (err, recordset) - Một cuộc gọi lại được gọi sau khi thực hiện xong hoặc xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
4

lỗi

  • ETIMEOUT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Yêu cầu hết thời gian chờ
  • YÊU CẦU (______062) - Thông báo từ SQL Server
  • ECANCEL (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Đã hủy
  • ENOCONN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Không có kết nối nào được chỉ định cho yêu cầu đó
  • ENOTOPEN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Chưa mở kết nối
  • ECONNCLOSED (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Kết nối bị đóng
  • ENOTBEGUN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch chưa bắt đầu
  • EABORT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch bị hủy bỏ (do người dùng hoặc do lỗi)

Bạn có thể kích hoạt nhiều bản ghi trong các truy vấn bằng lệnh

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
14


số lượng lớn (bảng, [tùy chọn,] [gọi lại])

Thực hiện chèn số lượng lớn

Tranh luận

  • bảng - ví dụ
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    83
  • tùy chọn - Đối tượng tùy chọn được chuyển qua trình điều khiển (chỉ hiện tại tẻ nhạt). Không bắt buộc. Nếu đối số là một chức năng, nó sẽ được coi là cuộc gọi lại
  • gọi lại (err, rowCount) - Một cuộc gọi lại được gọi sau khi quá trình chèn hàng loạt hoàn tất hoặc đã xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
5

QUAN TRỌNG. Luôn cho biết cột có rỗng hay không

TIỀN BOA. Nếu bạn đặt

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
16 thành
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
11, mô-đun sẽ kiểm tra xem bảng có tồn tại hay không trước khi bắt đầu gửi dữ liệu. Nếu không, nó sẽ tự động tạo nó. Bạn có thể chỉ định các cột khóa chính bằng cách đặt
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
18 cho các tùy chọn của cột. Hỗ trợ ràng buộc khóa chính trên nhiều cột

TIỀN BOA. Bạn cũng có thể tạo biến Bảng từ bất kỳ tập bản ghi nào với

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
19. Bạn có thể tùy chọn chỉ định tên loại bảng trong đối số đầu tiên

lỗi

  • ENAME (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Tên bảng phải được chỉ định để chèn hàng loạt
  • ETIMEOUT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Yêu cầu hết thời gian chờ
  • YÊU CẦU (______062) - Thông báo từ SQL Server
  • ECANCEL (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Đã hủy
  • ENOCONN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Không có kết nối nào được chỉ định cho yêu cầu đó
  • ENOTOPEN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Chưa mở kết nối
  • ECONNCLOSED (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Kết nối bị đóng
  • ENOTBEGUN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch chưa bắt đầu
  • EABORT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch bị hủy bỏ (do người dùng hoặc do lỗi)

sự hủy bỏ()

Hủy yêu cầu đang thực hiện. Trả lại

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
11 nếu gói hủy được gửi thành công

Thí dụ

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
6

Giao dịch

QUAN TRỌNG. luôn sử dụng lớp

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
52 để tạo giao dịch - nó đảm bảo rằng tất cả các yêu cầu của bạn được thực hiện trên một kết nối. Khi bạn gọi
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
31, một kết nối duy nhất sẽ được lấy từ nhóm kết nối và tất cả các yêu cầu tiếp theo (được khởi tạo với đối tượng
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
52) được thực hiện riêng trên kết nối này. Sau khi bạn gọi
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
33 hoặc
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
34, kết nối sẽ được giải phóng trở lại nhóm kết nối

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
7

Nếu bạn bỏ qua đối số kết nối, thay vào đó, kết nối toàn cầu sẽ được sử dụng

Thí dụ

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
8

Giao dịch cũng có thể được tạo bởi

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
35. Yêu cầu cũng có thể được tạo bởi
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
36

giao dịch bị hủy bỏ

Ví dụ này cho thấy cách bạn nên xử lý chính xác các lỗi giao dịch khi bật

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
37 (
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
28). Đã thêm vào 2. 0

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
9

Sự kiện

  • bắt đầu - Gửi đi khi giao dịch bắt đầu
  • cam kết - Gửi đi khi cam kết thành công
  • rollback(aborted) - Gửi đi khi rollback thành công với một đối số xác định xem giao dịch đã bị hủy bỏ (bởi người dùng hay do lỗi)

bắt đầu ([isolationLevel], [callback])

Bắt đầu giao dịch

Tranh luận

  • IsolationLevel - Kiểm soát hành vi khóa và lập phiên bản hàng của các câu lệnh TSQL do một kết nối đưa ra. Không bắt buộc.
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    39 theo mặc định. Đối với các giá trị có thể xem
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    40
  • gọi lại (err) - Một cuộc gọi lại được gọi sau khi giao dịch đã bắt đầu hoặc xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
0

lỗi

  • ENOTOPEN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Chưa mở kết nối
  • EALREADYBEGUN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch đã bắt đầu

cam kết ([gọi lại])

Cam kết giao dịch

Tranh luận

  • gọi lại (err) - Một cuộc gọi lại được gọi sau khi giao dịch đã được thực hiện hoặc xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
1

lỗi

  • ENOTBEGUN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch chưa bắt đầu
  • EREQINPROG (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Không thể thực hiện giao dịch. Có một yêu cầu đang được tiến hành

khôi phục ([gọi lại])

Phục hồi một giao dịch. Nếu hàng đợi không trống, tất cả các yêu cầu trong hàng đợi sẽ bị Hủy và giao dịch sẽ được đánh dấu là đã hủy bỏ

Tranh luận

  • gọi lại (err) - Một cuộc gọi lại được gọi sau khi giao dịch được khôi phục hoặc xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
2

lỗi

  • ENOTBEGUN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch chưa bắt đầu
  • EREQINPROG (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Không thể lùi giao dịch. Có một yêu cầu đang được tiến hành

Tuyên bố chuẩn bị

QUAN TRỌNG. luôn sử dụng lớp

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
47 để tạo các câu lệnh đã chuẩn bị - nó đảm bảo rằng tất cả các lần thực thi câu lệnh đã chuẩn bị của bạn được thực thi trên một kết nối. Khi bạn gọi
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
48, một kết nối duy nhất sẽ được lấy từ nhóm kết nối và tất cả các lần thực thi tiếp theo được thực hiện riêng trên kết nối này. Sau khi bạn gọi
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
49, kết nối sẽ được giải phóng trở lại nhóm kết nối

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
3

Nếu bạn bỏ qua đối số kết nối, thay vào đó, kết nối toàn cầu sẽ được sử dụng

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
4

QUAN TRỌNG. Hãy nhớ rằng mỗi câu lệnh đã chuẩn bị có nghĩa là một kết nối dành riêng từ nhóm. Đừng quên hủy một tuyên bố đã chuẩn bị khi bạn đã hoàn thành các truy vấn của mình

Bạn có thể thực hiện nhiều truy vấn đối với cùng một câu lệnh đã chuẩn bị nhưng bạn phải bỏ chuẩn bị câu lệnh khi sử dụng xong câu lệnh nếu không bạn sẽ khiến nhóm kết nối hết các kết nối khả dụng

TIỀN BOA. Bạn cũng có thể tạo các báo cáo đã chuẩn bị sẵn trong các giao dịch (_______150), nhưng hãy nhớ rằng bạn không thể thực hiện các yêu cầu khác trong giao dịch cho đến khi bạn gọi ____149


đầu vào (tên, loại)

Thêm một tham số đầu vào vào câu lệnh đã chuẩn bị

Tranh luận

  • tên - Tên của tham số đầu vào không có @ char
  • type - kiểu dữ liệu SQL của tham số đầu vào

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
5

Lỗi (đồng bộ)

  • EARGS (
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    52) - Số đối số không hợp lệ
  • EINJECT (
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    52) - Cảnh báo SQL injection

đầu ra (tên, loại)

Thêm một tham số đầu ra vào câu lệnh đã chuẩn bị

Tranh luận

  • tên - Tên của tham số đầu ra không có @ char
  • type - kiểu dữ liệu SQL của tham số đầu ra

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
6

Lỗi (đồng bộ)

  • EARGS (
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    52) - Số đối số không hợp lệ
  • EINJECT (
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    52) - Cảnh báo SQL injection

chuẩn bị (câu lệnh, [gọi lại])

Chuẩn bị một tuyên bố

Tranh luận

  • câu lệnh - câu lệnh T-SQL để chuẩn bị
  • gọi lại (err) - Một cuộc gọi lại được gọi sau khi quá trình chuẩn bị hoàn tất hoặc đã xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
7

lỗi

  • ENOTOPEN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    55) - Chưa mở kết nối
  • EALREADYPREPARED (
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    52) - Tuyên bố đã được chuẩn bị sẵn
  • ENOTBEGUN (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    68) - Giao dịch chưa bắt đầu

thực thi (giá trị, [gọi lại])

Thực hiện một tuyên bố đã chuẩn bị

Tranh luận

  • giá trị - Một đối tượng có tên tương ứng với tên của các tham số đã được thêm vào câu lệnh đã chuẩn bị trước khi nó được chuẩn bị
  • gọi lại (err) - Một cuộc gọi lại được gọi sau khi thực hiện xong hoặc xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
8

Bạn cũng có thể truyền phát yêu cầu đã thực hiện

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    // Query
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .query('select * from mytable where id = @input_parameter')
}).then(result => {
    console.dir(result)
}).catch(err => {
  // .. error checks
});
9

TIỀN BOA. Để tìm hiểu thêm về cách hoạt động của số lượng hàng bị ảnh hưởng, hãy xem phần Hàng bị ảnh hưởng

lỗi

  • ENOTPREPARED (
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    52) - Tuyên bố không được chuẩn bị
  • ETIMEOUT (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Yêu cầu hết thời gian chờ
  • YÊU CẦU (______062) - Thông báo từ SQL Server
  • ECANCEL (
    const sql = require('mssql')
    const sqlConfig = {
      user: process.env.DB_USER,
      password: process.env.DB_PWD,
      database: process.env.DB_NAME,
      server: 'localhost',
      pool: {
        max: 10,
        min: 0,
        idleTimeoutMillis: 30000
      },
      options: {
        encrypt: true, // for azure
        trustServerCertificate: false // change to true for local dev / self-signed certs
      }
    }
    
    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 mytable where id = ${value}`
      console.dir(result)
     } catch (err) {
      // .. error checks
     }
    }
    
    62) - Đã hủy

không chuẩn bị ([gọi lại])

Không chuẩn bị một tuyên bố chuẩn bị

Tranh luận

  • gọi lại (err) - Một cuộc gọi lại được gọi sau khi quá trình chuẩn bị hoàn tất hoặc xảy ra lỗi. Không bắt buộc. Nếu bỏ qua, trả về Promise

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
0

lỗi

  • ENOTPREPARED (
    const config = {
        user: '...',
        password: '...',
        server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
        database: '...',
    }
    
    52) - Tuyên bố không được chuẩn bị

CLI

Nếu bạn muốn thêm công cụ MSSQL CLI vào đường dẫn của mình, bạn phải cài đặt nó trên toàn cầu với

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
64

Thành lập

Tạo tệp cấu hình

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
65 (ở bất kỳ đâu). Cấu trúc của tệp giống như đối tượng cấu hình tiêu chuẩn

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
1

Thí dụ

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
2

Kết quả trong

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
3

Bạn cũng có thể truy vấn nhiều tập bản ghi

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
4

Kết quả trong

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
5

Nếu bạn bỏ qua đối số đường dẫn cấu hình, mssql sẽ cố tải nó từ thư mục làm việc hiện tại

Ghi đè cài đặt cấu hình

Bạn có thể ghi đè một số cài đặt cấu hình thông qua các tùy chọn CLI (

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
66,
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
67,
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
68,
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
69,
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
70)

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
6

Kết quả trong

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
7

Địa lý và Hình học

node-mssql có trình giải nén tích hợp sẵn cho các loại dữ liệu CLR Địa lý và Hình học

Địa lý

Các loại địa lý có thể được xây dựng theo nhiều cách khác nhau. Tham khảo kỹ tài liệu để xác minh thứ tự tọa độ;

truy vấn

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
8

kết quả trong

const sql = require('mssql')

sql.on('error', err => {
    // .. error handler
})

sql.connect(config).then(pool => {
    
    // Stored procedure
    
    return pool.request()
        .input('input_parameter', sql.Int, value)
        .output('output_parameter', sql.VarChar(50))
        .execute('procedure_name')
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})
9

GHI CHÚ. Bạn cũng sẽ thấy tọa độ

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
71 và
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
72 trong các điểm Địa lý được phân tích cú pháp, chúng không được khuyến nghị sử dụng. Do đó, chúng đã bị bỏ qua khỏi ví dụ này. Để tương thích, chúng vẫn bị lật (x, độ dịch chuyển theo chiều ngang, thay vào đó được sử dụng cho vĩ độ, theo chiều dọc) và do đó có nguy cơ khiến bạn hiểu nhầm. Thay vào đó, hãy ưu tiên sử dụng các thuộc tính
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
73 và
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
74

hình học

Các loại hình học cũng có thể được xây dựng theo nhiều cách. Không giống như Địa lý, chúng nhất quán trong việc luôn đặt x trước y. nút-mssql giải mã kết quả của truy vấn này

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
0

vào đối tượng JavaScript

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
1

Thông số có giá trị trong bảng (TVP)

Được hỗ trợ trên SQL Server 2008 trở lên. Bạn có thể chuyển bảng dữ liệu dưới dạng tham số cho thủ tục được lưu trữ. Đầu tiên, chúng ta phải tạo loại tùy chỉnh trong cơ sở dữ liệu của mình

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
2

Tiếp theo chúng ta sẽ cần một thủ tục được lưu trữ

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
3

Bây giờ hãy quay lại Node của chúng ta. ứng dụng js

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
4

Bạn có thể gửi bảng dưới dạng tham số cho thủ tục được lưu trữ

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
5

TIỀN BOA. Bạn cũng có thể tạo biến Bảng từ bất kỳ tập bản ghi nào với

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
19. Bạn có thể tùy chọn chỉ định tên loại bảng trong đối số đầu tiên

Bạn có thể xóa các hàng trong bảng để tạo khối dễ dàng hơn bằng cách sử dụng

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
76

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
6

Lược đồ phản hồi

Một đối tượng được trả về từ truy vấn cơ bản

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
77 sẽ giống như sau

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
7

Hàng bị ảnh hưởng

Nếu bạn đang thực hiện

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
78,
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
79 hoặc
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
80 trong một truy vấn, bạn có thể đọc số hàng bị ảnh hưởng. Biến
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
81 là một mảng số. Mỗi số đại diện cho số hàng bị ảnh hưởng bởi một câu lệnh

Ví dụ sử dụng Lời hứa

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
8

Ví dụ sử dụng gọi lại

const sql = require('mssql')

sql.connect(config).then(() => {
    return sql.query`select * from mytable where id = ${value}`
}).then(result => {
    console.dir(result)
}).catch(err => {
    // .. error checks
})

sql.on('error', err => {
    // .. error handler
})
9

Ví dụ sử dụng phát trực tuyến

Ngoài thuộc tính rowsAffected trong sự kiện đã hoàn thành, mỗi câu lệnh sẽ phát ra số lượng hàng bị ảnh hưởng khi hoàn thành

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
0

hỗ trợ JSON

SQL Server 2016 đã giới thiệu tuần tự hóa JSON tích hợp. Theo mặc định, JSON được trả về dưới dạng văn bản thuần túy trong một cột đặc biệt có tên là

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
82

Thí dụ

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
1

Kết quả trong

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
2

Bạn có thể bật trình phân tích cú pháp JSON tích hợp với

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
83. Sau khi bạn kích hoạt tính năng này, bộ bản ghi sẽ chứa các hàng đối tượng JS được phân tích cú pháp. Với cùng một ví dụ, kết quả sẽ như thế này

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
3

QUAN TRỌNG. Để điều này hoạt động, phải có chính xác một cột có tên

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
82 trong tập bản ghi

Thông tin thêm về hỗ trợ JSON có thể được tìm thấy trong tài liệu chính thức

Xử lý tên cột trùng lặp

Nếu truy vấn của bạn chứa các cột đầu ra có tên giống hệt nhau, hành vi mặc định của

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
85 sẽ chỉ trả về siêu dữ liệu cột cho cột cuối cùng có tên đó. Bạn cũng sẽ không phải lúc nào cũng có thể sắp xếp lại thứ tự các cột đầu ra được yêu cầu

hành vi mặc định

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
4

Kết quả trong

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
5

Bạn có thể sử dụng tham số cấu hình

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
86 để trả về các giá trị hàng dưới dạng mảng và thêm một mảng giá trị cột riêng biệt.
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
86 có thể được đặt trên toàn cầu trong quá trình kết nối ban đầu hoặc theo yêu cầu

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
6

Kết quả trong

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
7

Truyền trực tuyến tên cột trùng lặp

Khi sử dụng

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
86 với
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
94 được bật, đầu ra từ sự kiện
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
90 (như được mô tả trong Truyền phát) được trả về dưới dạng một mảng siêu dữ liệu cột, thay vì dưới dạng một đối tượng có khóa. Thứ tự của siêu dữ liệu cột do sự kiện
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
90 cung cấp sẽ khớp với thứ tự của các giá trị hàng khi bật
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
86

Hành vi mặc định (không có

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
86)

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
8

Kết quả trong

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    // Query

    new sql.Request().query('select 1 as number', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Stored Procedure

    new sql.Request()
    .input('input_parameter', sql.Int, value)
    .output('output_parameter', sql.VarChar(50))
    .execute('procedure_name', (err, result) => {
        // .. error checks

        console.dir(result)
    })

    // Using template literal

    const request = new sql.Request()
    request.query(request.template`select * from mytable where id = ${value}`, (err, result) => {
        // .. error checks
        console.dir(result)
    })
})

sql.on('error', err => {
    // .. error handler
})
9

Với

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
86

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})
0

Kết quả trong

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})
1

lỗi

Có 4 loại lỗi bạn có thể xử lý

  • ConnectionError - Lỗi liên quan đến kết nối và nhóm kết nối
  • TransactionError - Lỗi liên quan đến việc tạo, cam kết và khôi phục giao dịch
  • RequestError - Lỗi liên quan đến truy vấn và thực thi thủ tục được lưu trữ
  • PreparedStatementError - Các lỗi liên quan đến câu lệnh đã chuẩn bị

Các lỗi đó được khởi tạo trong mô-đun nút-mssql và ngăn xếp ban đầu của nó có thể bị cắt. Bạn luôn có thể truy cập lỗi ban đầu với

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
95

SQL Server có thể tạo ra nhiều lỗi cho một yêu cầu, do đó bạn có thể truy cập các lỗi trước đó bằng

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
96

Mã lỗi

Mỗi lỗi đã biết có thuộc tính

const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
97,
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
98 và
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
99

NameCodeMessage
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55ELOGINĐăng nhập không thành công.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55ETIMEOUTHết thời gian chờ kết nối.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55EDRIVERTrình điều khiển không xác định.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55EALREADYCONNECTEDCơ sở dữ liệu đã được kết nối.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55EALREADYCONNECTINGĐã kết nối với cơ sở dữ liệu.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55ENOTOPENKết nối chưa mở.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55EINSTLOOKUPKhông thể tra cứu phiên bản.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55ESOCKETLỗi ổ cắm.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
55ECONNCLOSEDKết nối đã đóng.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
68ENOTBEGUNGiao dịch chưa bắt đầu.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
68EALREADYBEGUNGiao dịch đã bắt đầu.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
68EREQINPROGKhông thể cam kết/khôi phục giao dịch. Có một yêu cầu đang được tiến hành.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
68EABORTGiao dịch đã bị hủy bỏ.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
62EREQUESTTin nhắn từ SQL Server. Đối tượng lỗi chứa các chi tiết bổ sung.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
62ECANCELĐã hủy.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
62ETIMEOUTYêu cầu thời gian chờ.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
62EARGSSố đối số không hợp lệ.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
62EINJECTSQL tiêm cảnh báo.
const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
62ENOCONNNKhông có kết nối nào được chỉ định cho yêu cầu đó.
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
52EARGSSố đối số không hợp lệ.
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
52Cảnh báo tiêm EINJECTSQL.
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
52EALREADYPREPAREDBáo cáo đã được chuẩn bị sẵn.
const config = {
    user: '...',
    password: '...',
    server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
    database: '...',
}
52ENOTPRAREDCâu lệnh chưa được chuẩn bị

Lỗi SQL chi tiết

Lỗi SQL (

const sql = require('mssql')
const sqlConfig = {
  user: process.env.DB_USER,
  password: process.env.DB_PWD,
  database: process.env.DB_NAME,
  server: 'localhost',
  pool: {
    max: 10,
    min: 0,
    idleTimeoutMillis: 30000
  },
  options: {
    encrypt: true, // for azure
    trustServerCertificate: false // change to true for local dev / self-signed certs
  }
}

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 mytable where id = ${value}`
  console.dir(result)
 } catch (err) {
  // .. error checks
 }
}
62 với
const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
24 bằng với
const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
25) chứa các chi tiết bổ sung

  • sai lầm. số - Số lỗi
  • sai lầm. trạng thái - Trạng thái lỗi, được sử dụng làm công cụ sửa đổi cho số
  • sai lầm. class - Loại (mức độ nghiêm trọng) của lỗi. Một lớp ít hơn 10 biểu thị một thông báo thông tin. Giải thích chi tiết có thể được tìm thấy ở đây
  • sai lầm. lineNumber - Số dòng trong lô SQL hoặc thủ tục được lưu trữ đã gây ra lỗi. Số dòng bắt đầu từ 1;
  • sai lầm. serverName - Tên máy chủ
  • sai lầm. procName - Tên thủ tục được lưu trữ

tin nhắn thông tin

Để nhận thông báo thông tin được tạo bởi lệnh

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
26 hoặc
const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
27, hãy sử dụng

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})
2

Cấu trúc thông điệp

  • thông tin. tin nhắn - tin nhắn
  • thông tin. số - Số tin nhắn
  • thông tin. trạng thái - Trạng thái tin nhắn, được sử dụng làm công cụ sửa đổi cho số
  • thông tin. lớp - Lớp (mức độ nghiêm trọng) của tin nhắn. Bằng hoặc thấp hơn 10. Giải thích chi tiết có thể được tìm thấy ở đây
  • thông tin. lineNumber - Số dòng trong lô SQL hoặc thủ tục được lưu trữ đã tạo thông báo. Số dòng bắt đầu từ 1;
  • thông tin. serverName - Tên máy chủ
  • thông tin. procName - Tên thủ tục được lưu trữ

Siêu dữ liệu bộ bản ghi có thể truy cập thông qua thuộc tính

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
28

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})
3

Cấu trúc cột ví dụ trên

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})
4

Loại dữ liệu

Bạn có thể xác định các loại dữ liệu với độ dài/độ chính xác/tỷ lệ

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})
5

Danh sách các loại dữ liệu được hỗ trợ

const sql = require('mssql')

sql.connect(config, err => {
    // .. error checks

    const request = new sql.Request()
    request.stream = true // You can set streaming differently for each request
    request.query('select * from verylargetable') // or request.execute(procedure)

    request.on('recordset', columns => {
        // Emitted once for each recordset in a query
    })

    request.on('row', row => {
        // Emitted for each row in a recordset
    })

    request.on('rowsaffected', rowCount => {
        // Emitted for each `INSERT`, `UPDATE` or `DELETE` statement
        // Requires NOCOUNT to be OFF (default)
    })

    request.on('error', err => {
        // May be emitted multiple times
    })

    request.on('done', result => {
        // Always emitted as the last one
    })
})

sql.on('error', err => {
    // .. error handler
})
6

Để thiết lập độ dài TỐI ĐA cho

const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
29,
const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
30 và
const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
31, hãy sử dụng độ dài
const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
32. Các loại
const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
33 và
const sql = require('mssql')

(async function () {
    try {
        let pool = await sql.connect(config)
        let result1 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .query('select * from mytable where id = @input_parameter')
            
        console.dir(result1)
    
        // Stored procedure
        
        let result2 = await pool.request()
            .input('input_parameter', sql.Int, value)
            .output('output_parameter', sql.VarChar(50))
            .execute('procedure_name')
        
        console.dir(result2)
    } catch (err) {
        // .. error checks
    }
})()

sql.on('error', err => {
    // .. error handler
})
34 không được hỗ trợ làm tham số đầu vào

tiêm SQL

Mô-đun này có tính năng bảo vệ SQL injection tích hợp sẵn. Luôn sử dụng các tham số hoặc ký tự mẫu được gắn thẻ để chuyển các giá trị đã làm sạch cho các truy vấn của bạn