sql - 必须声明标量变量“@studentID”
问题描述
当我输入 iD 值时,它显示:
必须声明标量变量“@studentID”。
****
这是我的课程代码
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();
}
解决方案
您将参数添加到错误的 SqlCommand。这个
cmd.Parameters.AddWithValue("@studentID", studentId);
应该
sqlcmd.Parameters.AddWithValue("@studentID", studentId);
推荐阅读
- scala - 如何从(键,值)对的值中找到百分比?
- spring-boot - 在 Spring-Boot 2.1.0 之后不读取 Hibernate spring.jpa.mapping-resources=hibernate.cfg.xml
- android - 无法使用 Google 使用 adb 提供的本机编解码器从内部存储播放视频
- python - 如何在python代码中调用Nodejs api?
- android - 调用 requiresPermission-annotated 方法时缺少权限提示
- excel - 合并来自不同 Excel 工作表基础列标题的数据
- python - 使用最小二乘法求解任意“Y”的矩阵乘法“AB=Y”中的“A”“B”
- android - 在 AppCompatActivity 中几乎全屏显示 DialogFragment,但仍保持工具栏可见
- sql-server - SSIS 错误“转换失败,因为数据值溢出指定类型”
- amazon-web-services - ECS 上蓝/绿部署所需的 Cloudformation 脚本