简体   繁体   English

将SQL Server数据转换为Array时,特定类型转换无效

[英]Specific cast is not valid while converting SQL Server data to Array

D B

Database: 数据库:

I try to convert SQL Server data to an array, but I got an error: 我尝试将SQL Server数据转换为数组,但出现错误:

Specific cast is not valid 特定的强制转换无效

This is my code: 这是我的代码:

string query = "select part1,part2,part3 from Table_3 where id ='" + textBox1.Text + "'";
int[] arr = new int[] { };
SqlCommand cmd = new SqlCommand(query, con);

SqlDataReader myReader;

try
{
    con.Open();

    myReader = cmd.ExecuteReader();

    while (myReader.Read())
    {
        arr[i] = myReader.GetInt16(1);
        i = i+1;
    }

    con.Close();
    MessageBox.Show(arr[0].ToString());
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}

There are a couple of problems here. 这里有两个问题。 The most likely immediate problem is that the data is not in fact Int16 - usually Int32 ( int ) is more common, so the GetInt16 is probably wrong. 最可能的直接问题是数据实际上不是Int16通常Int32int )更常见,因此GetInt16可能是错误的。

Arrays are not resizeable. 数组不可调整大小。 If you create a zero-length array, it will always be zero length . 如果创建零长度数组,则它将始终为零长度 You cannot add any values to it. 您不能为其添加任何值。

I find it curious that you're reading four columns but only consuming the second one - but that won't actually cause a failure. 我觉得很奇怪 ,您正在阅读四列,但仅消耗第二列-但这实际上不会导致失败。

You only seem to actually want the first value, not all of them - is an array even needed? 您似乎实际上只想要第一个值,而不是全部都需要-甚至需要一个数组吗?

There are a few things relating to disposing the reader, but they're easily fixed. 有一些与配置阅读器有关的事情,但是很容易解决。

And: never ever concatenate input into SQL. 并且:永远不要将输入连接到SQL。

The easiest way to fix all of these is with a tool like "Dapper": 解决所有这些问题的最简单方法是使用“ Dapper”之类的工具:

  • it knows how to convert between primitive types 它知道如何在原始类型之间进行转换
  • it makes it easy to correctly handle readers 它使正确处理读者变得容易
  • it makes it easy to correctly parameterize inputs 它使正确正确设置输入参数变得容易
  • it makes it easy to handle results as lists, arrays, etc 它使处理结果如列表,数组等变得容易
int[] arr = con.Query<int>("select part2 from Table_3 where id = @id",
    new { id = textBox1.Text }).ToArray();

or for just the single (first) result: 或仅针对单个(第一个)结果:

int val = con.QueryFirst<int>("select part2 from Table_3 where id = @id",
    new { id = textBox1.Text });

Note: if the data is actually defined as bit , then you'll want bool / Boolean in .NET. 注意:如果数据实际上定义为bit ,那么您将需要.NET中的bool / Boolean

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM