如何使用SqlDataReader提取值?

问题描述:

我想使用SqlDataReader从数据库提取值。此代码运行正常,当我只在while循环写student_idprogram_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(); 
+0

什么是我的错误? –

+1

是'int'类型的'session_id'? –

+0

是的它是int类型的。 –

我怀疑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); 
} 

我强烈建议使用调试器,放置一个断点,看看究竟收到了什么。

+0

我已经使用调试器,它给我的类型操作系统session_id是Int32。虽然在数据库中我只使用int。 –

+0

好的谢谢你每1 ...发现我的错误..有一个数据库中的问题.. –

+0

这很好:-) –

Propably你的价值不是一个INT32尝试转换到INT16int64

Convert(INT16,dr.GetValue(2));

你可以转换到指定的类型

Convert(INT64,dr.GetValue(2));

为了更好地帮助你应该发布您的数据库创建队列