简体   繁体   中英

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:

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.

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.

The easiest way to fix all of these is with a tool like "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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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