Home  >  Article  >  Backend Development  >  Perfect solution to the invalid conversion specified by SqlDataReader

Perfect solution to the invalid conversion specified by SqlDataReader

巴扎黑
巴扎黑Original
2017-08-08 13:21:172732browse

This article mainly introduces in detail the solution to the invalid specified conversion of SqlDataReader, which has certain reference value. Interested friends can refer to

The solution to the invalid specified conversion of SqlDataReader. For details The content is as follows


##

//获取最新显示顺序数据
      string str = string.Format(@"if exists(select ShowOrder from GIS_FuncDefaultLayer where GISFuncId = {0})
                           select max(ShowOrder) as ShowOrder from GIS_FuncDefaultLayer where GISFuncId ={0}
                           else select '0' as ShowOrder", GISFuncId); 
      IDataReader dataReader = helper.ExecuteReader(CommandType.Text, str);
      if (dataReader.Read())//判断当前功能Id下是否有数据
      {
        //读取赋值
        try
        {
          showOrder = dataReader.GetInt32(0);
          
        }
        catch (Exception ex)
        {

          HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(ex.Message) };
          return result;
        }
        
      }
dataReader.Close();//关闭

SqlDataReader’s own GetInt32 (and others such as GerString, etc.) method


It only obtains the columns of the corresponding data type in the database and does not have the function of type conversion, so it cannot be used like this

SolutionThere are two types

1. If you need to return int type, then the field in the database is defined as int type, then GetInt32 is feasible.

2. If the int type is not defined in the database, and you want to return int type, Then first use the corresponding type in the database to Get it, and then convert it
such as int.Parse(selectunitidread.GetString(0))
If you do not need to return the int type, as you wrote above, finally It is converted into string
and the type in the database is varchar corresponding to string, then you can directly assign the following value
For example: rmoutbackinfo.UnitId = selectunitidread.GetString(0)
without further conversion for string


//解决
showOrder=int.Parse(dataReader.GetString(0));

The above is the detailed content of Perfect solution to the invalid conversion specified by SqlDataReader. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn