0

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))
2
  • I don't see how cmd is used in SqlHelper. What is the relationship? Commented Apr 23, 2010 at 19:44
  • ya I just realized that sqlhelper code was calling another class for execution, so I changed the code took out the sqlhelper and it's wotking fine now Commented Apr 29, 2010 at 20:20

1 Answer 1

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

The SqlHelper class is a utility class that can be used to execute commands in a SQL Server database. you can more about it here: forums.asp.net/t/941983.aspx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.