C#: SQL Server ADO.NET connection

Stay organized with collections Save and categorize content based on your preferences.

Demonstrates executing a SQL INSERT statement by opening and closing a connection to Cloud SQL for SQL Server using the ADO.NET System.Data.Common package.

Code sample


insertTimestamp = DateTime.UtcNow;
    using(var connection = new SqlConnection(_connectionString.ConnectionString))
        // 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;
            var timeCast = insertVoteCommand.CreateParameter();
            timeCast.ParameterName = "@time_cast";
            timeCast.DbType = DbType.DateTime;
            timeCast.Value = insertTimestamp;
            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);

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.