首页 > 解决方案 > 必须声明标量变量“@studentID”

问题描述

当我输入 iD 值时,它显示:

必须声明标量变量“@studentID”。

当我输入 iD 值时,它显示****必须声明标量变量****

这是我的课程代码

public void Add()
{
    SqlConnection sqlCon = new SqlConnection("server = (LocalDB)\\MSSQLLocalDB ; Database = Online Medical Store; integrated security = true");
    sqlCon.Open();
    SqlCommand cmd = new SqlCommand("select StudentID, LastName, FirstName, FatherName, Address, City, Contact, EmailAddress from tblStudents where " +
        "StudentID=@studentID and LastName=@lastName and FirstName=@firstName  and FatherName=@fatherName and Address=@address and City=@city and Contact=@contact" +
        " and EmailAddress=@emailAddress ", sqlCon);
    cmd.Parameters.AddWithValue("@studentID", studentId);
    cmd.Parameters.AddWithValue("@lastName", LastName);
    cmd.Parameters.AddWithValue("@firstName", FirstName);
    cmd.Parameters.AddWithValue("@fatherName", FatherName);
    cmd.Parameters.AddWithValue("@address", Address);
    cmd.Parameters.AddWithValue("@city", City);
    cmd.Parameters.AddWithValue("@contact", Contact);
    cmd.Parameters.AddWithValue("@emailAddress", EmailAddress);
    SqlDataReader Dr = cmd.ExecuteReader();

    if (Dr.HasRows == true)
    {
        throw new Exception("This Record is already Exists");
    }
    else
    {
        SqlConnection con = new SqlConnection("server = (LocalDB)\\MSSQLLocalDB ; Database = Online Medical Store; integrated security = true");
        con.Open();
        SqlCommand sqlcmd = new SqlCommand
            ("insert into tblStudents (StudentID,LastName,FirstName," +
            "FatherName,Address, City, Contact, EmailAddress) " +
            "values (@studentID,@lastName,@firstName,@fatherName,@address," +
            "@city, @contact,@emailAddress)", con);
        cmd.Parameters.AddWithValue("@studentID", studentId);
        cmd.Parameters.AddWithValue("@lastName", LastName);
        cmd.Parameters.AddWithValue("@firstName", FirstName);
        cmd.Parameters.AddWithValue("@fatherName", FatherName);
        cmd.Parameters.AddWithValue("@address", Address);
        cmd.Parameters.AddWithValue("@city", City);
        cmd.Parameters.AddWithValue("@contact", Contact);
        cmd.Parameters.AddWithValue("@emailAddress", EmailAddress);
        sqlcmd.ExecuteNonQuery();

    }
    sqlCon.Close();
}

标签: sqlasp.netsql-serverclass

解决方案


您将参数添加到错误的 SqlCommand。这个

cmd.Parameters.AddWithValue("@studentID", studentId);

应该

sqlcmd.Parameters.AddWithValue("@studentID", studentId);

推荐阅读