I have this error : Must declare the scalar variable "@Login".
My code :
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["intranetv2"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("insert into [MyBase].[Dbo].[LogErrors] (Username, StackTrace, ShortDescription, DetailDescription, ErrorType) VALUES (@Login, @Stack, @Message, @Txt, @Source)", conn);
SqlParameter param = new SqlParameter();
param.ParameterName = "Login";
param.Value = user.Login;
param.ParameterName = "Stack";
param.Value = ex.StackTrace;
param.ParameterName = "Message";
param.Value = ex.Message;
param.ParameterName = "Txt";
param.Value = Txt;
param.ParameterName = "Source";
param.Value = ex.Source;
// 3. add new parameter to command object
cmd.Parameters.Add(param);
conn.Open();
return cmd.ExecuteNonQuery();
}
I have try with th e'@' in the param but i have the same error.
The problem is that you're constantly changing the value of 'param', then only adding the very last version.
Try the following instead:
The way you are going about it, only the last parameter is getting added. There are several ways of adding parameters to the command object and the one below is among the easiest:
There is a small mistake. Here is rectified code
}
Thanks
You must create a new SqlParameter for each Parameter, it should be like this:
You override
params
value and only ever add one parameter to the query. Which isSource
I'd recommend you create a new variable or use
AddWithValue
.etc.
To use
AddWithValue
you can do:You only added the last parameter to the parameter list.
Better would be this: