I started learning C# last week and I'm now having trouble with an INSERT sql statement. I used the following code, then I tell you what happens.
private void AddNewUserToDataBase(User user)
{
string commandText = "INSERT INTO User (firstName,lastName,adress,town,favoriteCurrency) " +
"VALUES (@firstName,@lastName,@adress,@town,@favoriteCurrency)";
using (SqlConnection connection = new SqlConnection(global::Laboratoire1.Properties.Settings.Default.Database1ConnectionString))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = commandText;
command.CommandType = CommandType.Text;
// je passe les paramètres ici pour éviter les erreurs au niveau du string commande
command.Parameters.Add(new SqlParameter("@firstName", user.getFirstName())); // autre façon plus générale
command.Parameters.Add(new SqlParameter("@lastName", user.getLastName()));
command.Parameters.Add(new SqlParameter("@adress", user.getAdress()));
command.Parameters.Add(new SqlParameter("@town", user.getTown()));
command.Parameters.Add(new SqlParameter("@favoriteCurrency", user.getFavoriteCurrencyId()));
try
{
connection.Open();
command.ExecuteNonQuery();
connection.Close();
}
catch (SqlException ex)
{
MessageBox.Show("Une erreur s'est produite.");
}
}
}
}
My program do not crashes and the exception message box shows up. I've trying to understand my error and changing the syntax of my command.Parameters.Add, but it still doesn't work :/.
After changing the catch block to display the exception instead of swallowing it, it throws:
Incorrect syntax near the keyword 'User'