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
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
[[["Easy to understand","easyToUnderstand","thumb-up"],["Solved my problem","solvedMyProblem","thumb-up"],["Other","otherUp","thumb-up"]],[["Hard to understand","hardToUnderstand","thumb-down"],["Incorrect information or sample code","incorrectInformationOrSampleCode","thumb-down"],["Missing the information/samples I need","missingTheInformationSamplesINeed","thumb-down"],["Other","otherDown","thumb-down"]],[],[],[],null,["# C#: SQL Server ADO.NET connection\n\nDemonstrates 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.\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud SQL for SQL Server, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n insertTimestamp = DateTime.UtcNow;\n try\n {\n using(var connection = new SqlConnection(_connectionString.ConnectionString))\n { \n connection.OpenWithRetry();\n // Insert a vote for SPACE or TAB with a timestamp.\n using (var insertVoteCommand = connection.CreateCommand())\n {\n insertVoteCommand.CommandText =\n @\"INSERT INTO votes (candidate, time_cast) VALUES (@candidate, @time_cast)\";\n var candidate = insertVoteCommand.CreateParameter();\n candidate.ParameterName = \"@candidate\";\n candidate.DbType = DbType.String;\n candidate.Value = team;\n insertVoteCommand.Parameters.Add(candidate);\n var timeCast = insertVoteCommand.CreateParameter();\n timeCast.ParameterName = \"@time_cast\";\n timeCast.DbType = DbType.DateTime;\n timeCast.Value = insertTimestamp;\n insertVoteCommand.Parameters.Add(timeCast);\n await insertVoteCommand.ExecuteNonQueryAsync();\n }\n }\n return Content($\"Vote successfully cast for '{team}' at time {insertTimestamp}!\");\n }\n catch (Exception ex)\n {\n // If something goes wrong, handle the error in this\n // section. This might involve retrying or adjusting\n // parameters depending on the situation.\n return StatusCode((int)HttpStatusCode.InternalServerError, ex);\n }\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=cloud_sql_sqlserver)."]]