C#: connessione ADO.NET di SQL Server

Dimostra l'esecuzione di un'istruzione SQL INSERT aprendo e chiudendo una connessione a Cloud SQL per SQL Server utilizzando il pacchetto ADO.NET System.Data.Common.

Per saperne di più

Per la documentazione dettagliata che include questo esempio di codice, consulta le seguenti risorse:

Esempio di codice

C#

insertTimestamp = DateTime.UtcNow;
try
{
    using(var connection = new SqlConnection(_connectionString.ConnectionString))
    {
        connection.OpenWithRetry();
        // Insert a vote for SPACE or TAB with a timestamp.
        using (var insertVoteCommand = connection.CreateCommand())
        {
            insertVoteCommand.CommandText =
                @"INSERT INTO votes (candidate, time_cast) VALUES (@candidate, @time_cast)";
            var candidate = insertVoteCommand.CreateParameter();
            candidate.ParameterName = "@candidate";
            candidate.DbType = DbType.String;
            candidate.Value = team;
            insertVoteCommand.Parameters.Add(candidate);
            var timeCast = insertVoteCommand.CreateParameter();
            timeCast.ParameterName = "@time_cast";
            timeCast.DbType = DbType.DateTime;
            timeCast.Value = insertTimestamp;
            insertVoteCommand.Parameters.Add(timeCast);
            await insertVoteCommand.ExecuteNonQueryAsync();
        }
    }
    return Content($"Vote successfully cast for '{team}' at time {insertTimestamp}!");
}
catch (Exception ex)
{
    // If something goes wrong, handle the error in this
    // section. This might involve retrying or adjusting
    // parameters depending on the situation.
    return StatusCode((int)HttpStatusCode.InternalServerError, ex);
}

Passaggi successivi

Per cercare e filtrare esempi di codice per altri prodotti Google Cloud, consulta il browser di esempio Google Cloud.