0

我正在尝试将字符串“testId”设置为从数据库中选择的值,但收到此错误:

没有为一个或多个必需参数指定值。

当我将代码保持原样时,它可以工作,但是当没有注释掉这些行时,我得到了错误

string testId = "";
protected void Page_Load(object sender, EventArgs e)
{

}
protected void registerButton_Click(object sender, EventArgs e)
{
    try
    {
        string connString = (@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=|DataDirectory|HorseDB.mdb");
        OleDbConnection conn = new OleDbConnection(connString);
        conn.Open();
        OleDbCommand cmd = conn.CreateCommand();
        OleDbCommand cmdSelect = conn.CreateCommand();
        cmd.CommandText = @"INSERT INTO [Users]([UserName], [UserSurname], [CellNumber], [Email], [Password])VALUES(@Name, @Surname, @Number, @Email, @Password)";
        //cmdSelect.CommandText = @"SELECT [UserId] FROM [Users] WHERE [Email] = @Email";
        cmd.Parameters.AddWithValue("@Name", registerNameTexbox.Text);
        cmd.Parameters.AddWithValue("@Surname", registerSurnameTextbox.Text);
        cmd.Parameters.AddWithValue("@Number", registerNumbertextbox.Text);
        cmd.Parameters.AddWithValue("@Email", registerEmailTextbox.Text);
        cmd.Parameters.AddWithValue("@Password", registerPasswordTextbox.Text);
        cmd.ExecuteNonQuery();
        //testId = cmdSelect.ExecuteNonQuery().ToString();
        conn.Close();
        paymentSite();

    }
    catch (OleDbException fail)
    {
        errorLabel1.Text = fail.Message;
    }
}
4

2 回答 2

3

You are adding your parameters to cmd but not to cmdSelect, even though your query for cmdSelect refers to @Email.

Add this line:

cmdSelect.Parameters.AddWithValue("@Email", registerEmailTextbox.Text);
于 2013-07-06T13:45:47.693 回答
0

看来您没有为 cmdSelect 命令添加所需的@Email 参数,如下所示:

cmdSelect.CommandText = @"SELECT [UserId] FROM [Users] WHERE [Email] = @Email";
Parameters.AddWithValue("@Email", registerEmailTextbox.Text ?? DBNull.Value);

我有一种预感,您的 ExecuteNonQuery 在此之后会正常工作。

此外,就像评论中提到的@Uwe-Keim 一样,作为最佳实践,您可能希望首先检查文本框中的空值。在片段中,我使用空合并运算符以基本形式附加了它。

于 2013-07-06T13:52:09.910 回答