J'ai une table "Student".
P_ID LastName FirstName Address City
1 Hansen Ola
2 Svendson Tove
3 Petterson Kari
4 Nilsen Johan
...and so on
Comment modifier le code d'édition en C#
string firstName = "Ola";
string lastName ="Hansen";
string address = "ABC";
string city = "Salzburg";
string connectionString = System.Configuration.ConfigurationManager
.ConnectionStrings["LocalDB"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "INSERT INTO Student (LastName, FirstName, Address, City)
VALUES (@ln, @fn, @add, @cit)";
command.Parameters.AddWithValue("@ln", lastName);
command.Parameters.AddWithValue("@fn", firstName);
command.Parameters.AddWithValue("@add", address);
command.Parameters.AddWithValue("@cit", city);
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
pour modifier une entrée où le champ Nom de famille a une valeur de nom et le champ Prénom une valeur de prénom.
Je ne veux pas l'utiliser comme ceci
UPDATE Persons SET Address='Nissestien 67', City='Sandnes'
WHERE LastName='Tjessem' AND FirstName='Jakob'
et j'ai modifié ma déclaration originale en
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City)
VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName +
"' AND FirstName='" + firstName+"'";
mais l'instruction n'est pas exécutée, pourquoi l'exception SQL est-elle levée ? Y a-t-il une solution à ce problème ?
Ce n'est pas une méthode correcte de mise à jour d'un enregistrement en SQL :
command.CommandText = "UPDATE Student(LastName, FirstName, Address, City) VALUES (@ln, @fn, @add, @cit) WHERE LastName='" + lastName + "' AND FirstName='" + firstName+"'";
Vous devriez l'écrire comme ceci :
command.CommandText = "UPDATE Student
SET Address = @add, City = @cit Where FirstName = @fn and LastName = @add";
Ensuite, vous ajoutez les paramètres de la même manière que vous les avez ajoutés pour l'opération d'insertion.
Je ne veux pas utiliser comme ça
C'est la syntaxe de l'instruction Update
en SQL, vous devez utiliser cette syntaxe sinon vous obtiendrez l'exception.
command.Text = "UPDATE Student SET Address = @add, City = @cit Where FirstName = @fn AND LastName = @ln";
et ajoutez ensuite vos paramètres en conséquence.
command.Parameters.AddWithValue("@ln", lastName);
command.Parameters.AddWithValue("@fn", firstName);
command.Parameters.AddWithValue("@add", address);
command.Parameters.AddWithValue("@cit", city);