Node.js:SQL Server - mssql 連線

示範如何使用 Node.js mssql 模組,開啟及關閉與 Cloud SQL for SQL Server 的連線,以便執行 SQL INSERT 陳述式。

深入探索

如需包含此程式碼範例的詳細說明文件,請參閱以下文件:

程式碼範例

Node.js

如要驗證 Cloud SQL for SQL Server,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

try {
  const stmt =
    'INSERT INTO votes (time_cast, candidate) VALUES (@timestamp, @team)';
  // Using a prepared statement protects against SQL injection attacks.
  // When prepare is called, a single connection is acquired from the connection pool
  // and all subsequent executions are executed exclusively on this connection.
  const ps = new mssql.PreparedStatement(pool);
  ps.input('timestamp', mssql.DateTime);
  ps.input('team', mssql.VarChar(6));
  await ps.prepare(stmt);
  await ps.execute({
    timestamp: timestamp,
    team: team,
  });
  await ps.unprepare();
} catch (err) {
  // If something goes wrong, handle the error in this section. This might
  // involve retrying or adjusting parameters depending on the situation.
  // ...
}

後續步驟

如要搜尋及篩選其他 Google Cloud 產品的程式碼範例,請參閱 Google Cloud 範例瀏覽器