【问题标题】:data reader specified cast is invalid?数据读取器指定的强制转换无效?
【发布时间】:2011-05-11 16:46:58
【问题描述】:

我正在使用 c# asp.net,只是尝试在提交数据后以只读格式显示数据。它用于培训,我的处理程序说没有参数化,(它不是用于实际部署);当我运行 select 命令时,我在第一行 GetInt32 抛出 specified cast is invalid 异常。值是整数,列设置为整数。我错过了什么?

string epl = "SELECT Entity, Employees, CA, MI, NY, NJ, Primex, EplLim, EplSir, Premium, Wage, Sublim, SubmissionId FROM EPL WHERE SubmissionId =" + x;
                    using (SqlCommand epcmd = new SqlCommand(epl, EplConn))
                    {
                        SqlDataReader epdr = epcmd.ExecuteReader();
                        epdr.Read();
                        LblEplShowEntity.Text = epdr.GetInt32(0).ToString();
                        LblEplShowTotalEmpl.Text = epdr.GetInt32(1).ToString();
                        LblEplShowCalEmpl.Text = epdr.GetInt32(2).ToString();
                        LblEplShowMichEmpl.Text = epdr.GetInt32(3).ToString();
                        LblEplShowNyEmpl.Text = epdr.GetInt32(4).ToString();
                        LblEplShowNjEmpl.Text = epdr.GetInt32(5).ToString();
                        LblEplShowPrimEx.Text = epdr.GetInt32(6).ToString();
                        LblEplShowLim.Text = epdr.GetInt32(7).ToString();
                        LblEplShowPrem.Text = epdr.GetInt32(8).ToString();
                        LblEplShowWage.Text = epdr.GetInt32(9).ToString();
                        LblEplShowInvestCost.Text = epdr.GetInt32(10).ToString();
                        epdr.Close();
                    }      

【问题讨论】:

  • 如果您要采用字符串表示形式(又名epdr["Entity"].ToString() 并在其上调用int.Parseint.TryParse,它仍然会给出错误吗?第1 列中返回的实际文本是什么? (索引 0)?

标签: c# asp.net sql-server visual-studio


【解决方案1】:

检查数据库列是否为 int。检查 DB Null 值做

LblEplShowEntity.Text = epdr.IsDBNull(0) ? string.Empty : epdr.GetInt32(0).ToString();

【讨论】:

    【解决方案2】:

    您的数据中有空值?这也会导致该异常。此外,请仔细检查该字段是否确实定义为整数,而不是例如浮点数。

    【讨论】:

    • 是的,不,正如我所说,值在那里,字段定义为 int。
    【解决方案3】:

    您应该知道 select 语句中每一列的确切数据类型。例如,如果实体列的类型为BIGINT,那么如果您尝试使用reader.GetInt32(),您将拥有InvalidCastException,因为您应该改用reader.GetInt64() 方法。

    其次,您应该分别处理 NULL 值。您应该检查 reader.IsDBNull(0) 或使用以下代码:

    int? entity = (int?)reader["Entity"];
    

    请注意,您可以使用字符串索引器从数据读取器中获取数据。这是更易读的方法。

    编辑:尝试将您的选择语句更改为:

    string epl = @"SELECT CAST(Entity AS INT) AS Entity, Employees, CA, MI, NY, NJ, Primex, EplLim, EplSir, Premium, Wage, Sublim, SubmissionId 
    FROM EPL WHERE SubmissionId =" + x;
    

    【讨论】:

      猜你喜欢
      • 2014-10-08
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 2018-05-27
      • 2014-07-30
      • 2012-06-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多