C#:SQL Server ADO.NET 连接

演示如何通过使用 ADO.NET System.Data.Common 软件包打开和关闭与 Cloud SQL for SQL Server 的连接来执行 SQL INSERT 语句。

代码示例

C#

如需向 Cloud SQL for SQL Server 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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);
}

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器