I am having a problem with my sql query in c#, basically it’s inline query with parameters, but when I run it it tells me that parameter 1 or parameter 2 is not there
here is my query declared on top of the page as public:
public const string InsertStmtUsersTable = "insert into Users (username, password, email, userTypeID, memberID, CM7Register) " +
"Values(@username, @password, @email, @userTypeID, @memberID,@CM7Register ); select @@identity";
this is my code for assigning the parameters, I know I am having problem so I am assigning the params twice:
Username =(cmd.Parameters["@username"].Value = row["username"].ToString()) as string; cmd.Parameters["@username"].Value = row["username"].ToString();
In 1 methopd it calls this query and tries to insert to table, here is the code:
Result = Convert.ToInt32(SqlHelper.ExecuteScalar(con, CommandType.Text,InsertStmtUsersTable));
Exact error message is: Must declare the variable ‘@username’.
Could this code be a problem, because all the previous coding is declared with in this using statement, except declaration of query, here the using statement:
using (SqlCommand cmd = new SqlCommand(InsertStmtUsersTable, con))
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
That is just all kinds of ugly. This could be a lot simpler (even though I’m not sure what SqlHelper does:
using(SqlConnection conn = new SqlConnection(connString))
{
conn.Open();
SqlCommand command = new SqlCommand(InsertStmtUsersTable, conn);
command.CommandType = CommandType.Text;
command.Parameters.Add(new SqlParameter("username", userNameString));
command.Parameters.Add(new SqlParameter("password", passwordString));
command.Parameters.Add(new SqlParameter("email", emailString));
command.Parameters.Add(new SqlParameter("userTypeId", userTypeId));
command.Parameters.Add(new SqlParameter("memberId", memberId));
// Rest of your Parameters here
var result = (int)command.ExecuteScalar();
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0