【问题标题】:Invalid Cast Exception with C#C# 的无效强制转换异常
【发布时间】:2020-03-11 11:27:17
【问题描述】:

我正在用 C# 和一个 MS Access 2007 数据库开发一个应用程序。

myTable 有 3 列:Number(Integer), Name(Long Text), Date(Date);

我正在尝试从 myTable 中读取一个值(整数),并尝试将其存储到 TOT 中以执行其他操作。 但我继续遇到错误 TOT = reader.GetInt32(x); 说“无效的转换异常”。

使用即时窗口,问题似乎出在reader.GetInt32(x)

代码如下:

OdbcConnection conn = new OdbcConnection("Dsn=My_Access_Database; Pwd=1234");
OdbcCommand cmd;
OdbcDataReader reader;
int TOT = 0;

conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "Select SUM(Number) AS col1 From myTable WHERE Name = '" + label1.Text + "' AND Date=#" + label2.Text + "#;";
reader = cmd.ExecuteReader();
while (reader.Read())
{
   int x= reader.GetOrdinal("col1");
   if (reader.IsDBNull(x))
   {
     label3.Text = "0.0";
     label4.Text = "0.0";
     label5.Text = "0.0";
   }
   else
   {
      TOT = reader.GetInt32(x);
      //Other things 
   }
}

当我在 Access 上执行查询时,它会起作用并给我想要的值。

【问题讨论】:

  • 我的猜测是 SUM(Number) 正在返回 double 或其他一些“非整数”类型。
  • 什么是 Int? TOT 是一种 Int 而不是 int ,你确定这是正确的吗?
  • 是的,绝对是,在我的代码中它是“int”,在这里输入错误。整数的 SUM 是否有可能返回非整数值?

标签: c# ms-access-2007


【解决方案1】:

好的解决了:

看起来我的 SUM(Number) 返回了一个 Double 值,即使该列是一个整数并填充了整数值。

因此,您应该将该值读取为双精度值并将其转换为 int。 代码如下:

OdbcConnection conn = new OdbcConnection("Dsn=My_Access_Database; Pwd=1234");
OdbcCommand cmd;
OdbcDataReader reader;
int TOT = 0;

conn.Open();
cmd = conn.CreateCommand();
cmd.CommandText = "Select SUM(Number) AS col1 From myTable WHERE Name = '" + label1.Text + "' AND Date=#" + label2.Text + "#;";
reader = cmd.ExecuteReader();
while (reader.Read())
{
   int x= reader.GetOrdinal("col1");
   if (reader.IsDBNull(x))
   {
     label3.Text = "0.0";
     label4.Text = "0.0";
     label5.Text = "0.0";
   }
   else
   {
      TOT = (int)(reader.GetInt32(x));
      //Other things 
   }
}

【讨论】:

    【解决方案2】:

    尝试使用TryParse方法:

    var result = reader.GetString(x);
    int.TryParse(result, out TOT);
    

    更新:

    尝试CAST你的总和到int

    cmd.CommandText = "Select CAST(SUM(Number) as INT) AS col1 From myTable WHERE Name = '" 
        + label1.Text + "' AND Date=#" + label2.Text + "#;";
    // the other code is omitted for the brevity
    else
    {
        TOT = reader.GetInt32(x);
    }
    

    【讨论】:

    • 说它不能从 System.Double 转换为 System.String。所以我们知道 SUM(Number) 是一个 Double。但是 Number 是一个 Integer 列,具有 Integer 值。
    • 我猜SUM() 总是返回一个双精度类型,即使它只是对整数求和。
    • 那么我要做的是 TOT = read.GetDouble() 然后将 TOT 转换为 int 吗?
    猜你喜欢
    • 2012-09-21
    • 2012-05-28
    • 2012-02-20
    • 1970-01-01
    • 2015-01-27
    • 2012-09-20
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多