我正在处理一个个人项目,该项目使用Microsoft SQL DB和Web层进行Rest API调用。我正在尝试使用SqlDataReader从数据库获取int32s和字符串。当我读字符串时,没有错误,但是当我尝试读整数时,我得到以下
`异常:System.IndexOutOfRangeException:'StudentID'
public StudentAccount FindStudentByID(int id)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
String sql = "SELECT FirstName, LastName,StudentBiography FROM [PersonTest].[dbo].[StudentAccounts] WHERE StudentID = @p1";
StudentAccount matchingStudent = new StudentAccount();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.Add("@p1", SqlDbType.Int).Value = id;
cmd.CommandType = CommandType.Text;
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
matchingStudent.StudentID = reader.GetInt32(reader.GetOrdinal("StudentID"));
matchingStudent.FirstName = reader["FirstName"].ToString();
matchingStudent.LastName = reader["LastName"].ToString();
matchingStudent.Biography = reader["StudentBiography"].ToString();
matchingStudent.CollegeID = reader.GetInt32(reader.GetOrdinal("COLLTB_CollegeID"));
}
reader.Close();
return matchingStudent;
}
}
}
StudentAccounts表如下:
StudentAccounts (StudentID, FirstName, LastName, StudentBiography, CollTB_CollegeID)
StudentID
是主键。
如果我弄乱了格式或任何内容,我会提前道歉,这是我第一次在该论坛上发帖。谢谢!
答案 0 :(得分:1)
您没有将StudentID
语句中的列返回COLLTB_CollegeID
或select
...
String sql = "SELECT FirstName, LastName,StudentBiography FROM [PersonTest].[dbo].[StudentAccounts] WHERE StudentID = @p1";
应该是...
String sql = "SELECT StudentID, FirstName, LastName, StudentBiography, COLLTB_CollegeID FROM [PersonTest].[dbo].[StudentAccounts] WHERE StudentID = @p1";
尽管您似乎两次设置了matchingStudent.CollegeID
,但看起来您返回列中的StudentID
看起来仍然没有!
答案 1 :(得分:0)
您正在使用:
matchingStudent.CollegeID = reader.GetInt32(reader.GetOrdinal("StudentID"));
这意味着:
var columnNumber = reader.GetOrdinal("StudentID");
matchingStudent.CollegeID = reader.GetInt32(columnNumber);
现在,第一次呼叫失败,因为StudentID
语句中没有SELECT
。包括要阅读的列。 COLLTB_CollegeID
也是如此。
所以:
var sql = "SELECT FirstName, LastName, StudentBiography, StudentID, COLLTB_CollegeID FROM [PersonTest].[dbo].[StudentAccounts] WHERE StudentID = @p1";
此外,您正在将结果分配给错误的属性:
matchingStudent.StudentID = reader.GetInt32(reader.GetOrdinal("StudentID"));