如何使用SqlDataReader提取值?
我想使用SqlDataReader
从数据库提取值。此代码运行正常,当我只在while循环写student_id
和program_id
,但将在session_id
的错误:如何使用SqlDataReader提取值?
指定的转换是无效
代码:
string student_name = items.Cells["student_name"].Value.ToString();
string query_select_student = "SELECT student_id, program_id, session_id, department_id FROM student WHERE student_name = '" + student_name + "' ";
SqlDataReader dr = DataAccess.selectDataReader(query_select_student);
while (dr.Read())
{
student_id = (int)dr.GetValue(0);
program_id = (int)dr.GetValue(1);
session_id = (int)dr.GetValue(2);
department_id = (int)dr.GetValue(3);
}
dr.Close();
我怀疑session_id
您从数据库中获得的值是而不是和int
或值可能是null。
试试这个。
while (dr.Read())
{
student_id = (int)dr.GetValue(0);
program_id = (int)dr.GetValue(1);
session_id = dr.IsDBNull(2)? default(int) : (int)dr.GetValue(2);
department_id = (int)dr.GetValue(3);
}
我强烈建议使用调试器,放置一个断点,看看究竟收到了什么。
我已经使用调试器,它给我的类型操作系统session_id是Int32。虽然在数据库中我只使用int。 –
好的谢谢你每1 ...发现我的错误..有一个数据库中的问题.. –
这很好:-) –
Propably你的价值不是一个INT32
尝试转换到INT16
或int64
与
Convert(INT16,dr.GetValue(2));
你可以转换到指定的类型
Convert(INT64,dr.GetValue(2));
为了更好地帮助你应该发布您的数据库创建队列
什么是我的错误? –
是'int'类型的'session_id'? –
是的它是int类型的。 –