Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

c# - Sql inline query with parameters. Parameter is not read when the query is executed

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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...