c # variable en commande sql

ssortingng alpha="this is text"; ssortingng sql = "INSERT INTO dokimastikospinakas (pliroforia) VALUES ('alpha')"; 

Quelle est la bonne syntaxe pour passer la variable ac # dans une commande SQL?

Voici une méthode très simple:

 var yourTextValue = "this is text"; using (var db = new SqlConnection()) { db.Open(); var command = new SqlCommand("INSERT INTO dokimastikospinakas (pliroforia) VALUES (@textValue);", db); command.Parameters.AddWithValue("@textValue", yourTextValue); command.ExecuteNonQuery(); } 

EDIT : Bien sûr, vous aurez besoin d’une chaîne de connexion pour le constructeur SqlConnection . Et modifié les noms de variables à la demande générale.

Pour éviter les vulnérabilités d’injection SQL, je recommande:

 ssortingng alpha="this is text"; SqlCommand sqlComm = new SqlCommand(); sqlComm.CommandText = "INSERT INTO dokimastikospinakas (pliroforia) VALUES (@var)"; sqlComm.AddWithValue("@var", alpha); 

..etc.

Rechercher dans l’utilisation de requêtes paramétrées.

 SqlCommand command = new SqlCommand(); command.Parameters.Add("@alpha").Value = alpha; command.CommandText = sql; 

Et votre requête ressemblerait à ceci:

 ssortingng sql = "INSERT INTO dokimastikospinakas (pliroforia) VALUES (@alpha)"; 
 ssortingng insert = "INSERT INTO dokimastikospinakas (pliroforia) VALUES (@alpha)"; using (SqlConnection connection = new SqlConnection(...)) { connection.Open(); using (SqlCommand command = new SqlCommand(insert, connection)) { command.Parameters.Add("@alpha", alpha); command.ExecuteNonQuery(); } } 

Utilisez-vous ADO.NET? Ensuite, les requêtes paramétrées sont ce que vous voulez:

 IDbCommand command = new IDbCommand(); // Set up command connection command.Text = "INSERT INTO dokimastikospinakas (pliroforia) VALUES (@alpha)"; command.Parameters.Add(new SqlParameter("@alpha", alpha)); 

L’extrait de code ci-dessus dépend bien sûr du type de firebase database que vous utilisez (en particulier du type de SqlParameter que vous ajoutez.

Exemple d’utilisation d’un object OracleCommand: OraCon est OracleConnection.

 ssortingng sql = "INSERT INTO dokimastikospinakas (pliroforia) VALUES ( :Alpha )"; OracleCommand cmd = new OracleCommand(sql, OraCon); cmd.CommandType = CommandType.Text; cmd.Parameters.Add(":Alpha", alpha); cmd.ExecuteNonQuery(); 
 ssortingng alpha; ssortingng sql = "INSERT INTO dokimastikospinakas (pliroforia) VALUES ('" + alpha + "')"; 

c’est la façon la plus simple de le faire, mais ce n’est pas à l’abri d’attaques par injection SQL. Au lieu de cela, vous devez d’abord vérifier la valeur de alpha pour vous assurer qu’elle peut être utilisée en toute sécurité dans une requête.