Ouvrir ou fermer une connexion lors de l'utilisation d'ADO.NET
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Exécutez une instruction SQL INSERT pour ouvrir et fermer une connexion à Cloud SQL pour MySQL à l'aide du package System.Data.Common d'ADO.NET.
Exemple de code
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],[],[],[],null,["# Open or close a connection when using ADO.NET\n\nRun a SQL INSERT statement to open and close a connection to Cloud SQL for MySQL by using the ADO.NET System.Data.Common package.\n\nCode sample\n-----------\n\n### C#\n\n\nTo authenticate to Cloud SQL for MySQL, 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 MySqlConnection(_connectionString.ConnectionString))\n { \n connection.OpenWithRetry();\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_mysql)."]]