2015-10-16 38 views
1

我试着去接受一个字符串转换为整数,代码是这样的:如何转换避免System.FormatException的数据类型?

 int menu = 3 
     int orden = 0; 
     string query = @"select max(oppord)+1 as orden 
         from rhlibry.vaoppfi 
         where pincor = " + menu; 
     OdbcConnection cn = new OdbcConnection("dsn=RHLIBRY;uid=PC00;pwd=PC00;"); 
     OdbcCommand cmd = new OdbcCommand(query, cn); 
     cn.Open(); 
     OdbcDataReader oa = cmd.ExecuteReader(); 
     while (oa.Read()) 
     { 
      orden = Int32.Parse(oa["orden"].ToString()); 
     } 
     return orden; 

以字符串格式SQL查询返回“奥登”,我需要转换成整型。

orden = Int32.Parse(oa["orden"].ToString());返回System.FormatException类型的错误。

为什么?我做错了?

请帮帮我!

谢谢

+0

什么是'oppord'的数据类型? –

+0

stephen,数据类型是数字(8,0)在数据库中 –

+0

您在该表中有任何记录吗?这可能是因为oa [“orden”]是'DBNull.Value' –

回答

2

这可能是因为您的查询返回空值。

假设您有一个具有值为1,2,3的Id列的Category表。 如果您运行此查询:

SELECT Max(Id)+1 As Id From Category WHERE Id = -1 

,您会收到这样的结果:

Id 
---------- 
NULL 

所以,当你使用Int32.Parse(oa["Id"].ToString())您会收到出现FormatException。

作为一个修复你可以使用:

SELECT ISNULL(Max(Id),0)+1 As Id From Category WHERE Id = -1 

此外,如果你的业务逻辑允许的话,你可以删除的标准。

此外,在C#的一面,你可以使用int.TryParse():

int id = 0; 
var idObject= oa["Id"]; 
if (idObject!=null) 
    int.TryParse(oa["Id"].ToString(), out id); 
+0

'TryParse'是我的第一个想法 - 太棒了 –

+0

欢迎:) –

相关问题