Node.js: conexión a SQL Server mediante mssql

Muestra cómo ejecutar una instrucción SQL INSERT abriendo y cerrando una conexión a Cloud SQL para SQL Server mediante el módulo mssql de Node.js.

Investigar más

Para obtener documentación detallada que incluya este código de muestra, consulta lo siguiente:

Código de ejemplo

Node.js

Para autenticarte en Cloud SQL para SQL Server, configura las credenciales predeterminadas de la aplicación. Para obtener más información, consulta el artículo Configurar la autenticación en un entorno de desarrollo local.

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.
  // ...
}

Siguientes pasos

Para buscar y filtrar ejemplos de código de otros Google Cloud productos, consulta el Google Cloud navegador de ejemplos.