我有四个班级的学生,课程,注册和UpdateScore
在StudentClass中:
public class Student
{
public string studID { get; set; }
public string name { get; set; }
public Student() { }
public Student(string StudID,string Name)
{
this.studID = StudID;
this.name = Name;
}
}
在CourseClass中
public class Course
{
public string courseID { get; set; }
public string title { get; set; }
public int credits { get; set; }
public Course()
{
}
public Course(string CourseID, string Name, int Credits)
{
this.courseID = CourseID;
this.title = Name;
this.credits = Credits;
}
}
在注册类
public class Registration
{
public Student studentData { get; set; }
public Course courseData { get; set; }
public DateTime DOEnroll { get; set; }
public Registration ()
{
}
public Registration (Student sData, Course cData, DateTime doe)
{
this.studentData = sData;
this.courseData = cData;
this.DOEnroll = doe;
}
}
在UpdateScore类
中 public class UpdateScore
{
public Registration enrollData { get; set; }
public int score { get; set; }
public UpdateScore () { }
public UpdateScore (Registration enrData, int sco)
{
this.enrollData = enrData;
this.score = sco;
}
}
现在我正在使用此查询进行更新,但在studentID和CourseID中显示空数据
代码是:
public static void Update(UpdateScore score)
{
SqlConnection conn = DB.GetConnection();
try
{
conn.Open();
string selectStm = "UPDATE EnrollmentTable set Score = @Score where StudentID = @StudentID AND CourseID = @CourseID";
SqlCommand command = new SqlCommand(selectStm, conn);
SqlParameter param1 = new SqlParameter();
SqlParameter param2 = new SqlParameter();
SqlParameter param3 = new SqlParameter();
param1.ParameterName = "@StudentID";
param2.ParameterName = "@CourseID";
param3.ParameterName = "@Score";
Student st = new Student();
Course cr = new Course();
Registration enr = new Registration ();
enr.courseData = cr;
enr.studentData = st;
score.enrollData = enr;
param1.Value = st.studID ;
param2.Value = cr.courseID;
param3.Value = score.score;
command.Parameters.Add(param1);
command.Parameters.Add(param2);
command.Parameters.Add(param3);
int i = command.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
conn.Close();//Close Connection
}
}
它给了我这个例外
参数化查询'(@StudentID nvarchar(4000),@ CourseID nvarchar(4000),@ Score int)U'需要参数'@StudentID',这是未提供的。
您能否告诉我如何获取StudentID和CourseID中的值?
答案 0 :(得分:1)
参数名称本身不应该包含@。变化
param1.ParameterName = "@StudentID";
param2.ParameterName = "@CourseID";
param3.ParameterName = "@Score";
到
param1.ParameterName = "StudentID";
param2.ParameterName = "CourseID";
param3.ParameterName = "Score";
此外,
答案 1 :(得分:0)
Eric为您的问题提供了正确的解释。我想指出另一个问题。
在你的班级学生中,你后来分配给param1.Value的autoproperty studID是一个字符串。 C#中的字符串是对象,因此它们的默认值为null。您的更新代码不会为studID分配任何值,因此当您将其分配给param1.Value时,您实际上是将空值分配给param1.Value。这可能不是你想要的。
与CourseID相同。
假设您在Update方法中收到的UpdateScore已按照对象模型的建议正确构建了其中的所有数据,则不应创建新的Student或Course对象。相反,做一些像
这样的事情param1.Value = score.enrollData.studentData.studID;
与其他信息类似。
继续编码!
注意:这看起来很像家庭作业,所以你也应该抓住这个机会思考代码在做什么,也可以用调试器运行它来看看如何分配值,等等。我已经概述了一些帮助但是我不会为你做全部工作: - )