![](/img/trans.png)
[英]Specified cast is not valid while fetching column details from SQL Server
[英]Specific cast is not valid while converting SQL Server data to Array
数据库:
我尝试将SQL Server数据转换为数组,但出现错误:
特定的强制转换无效
这是我的代码:
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);
}
这里有两个问题。 最可能的直接问题是数据实际上不是Int16
通常Int32
( int
)更常见,因此GetInt16
可能是错误的。
数组不可调整大小。 如果创建零长度数组,则它将始终为零长度 。 您不能为其添加任何值。
我觉得很奇怪 ,您正在阅读四列,但仅消耗第二列-但这实际上不会导致失败。
您似乎实际上只想要第一个值,而不是全部都需要-甚至需要一个数组吗?
有一些与配置阅读器有关的事情,但是很容易解决。
并且:永远不要将输入连接到SQL。
解决所有这些问题的最简单方法是使用“ Dapper”之类的工具:
int[] arr = con.Query<int>("select part2 from Table_3 where id = @id",
new { id = textBox1.Text }).ToArray();
或仅针对单个(第一个)结果:
int val = con.QueryFirst<int>("select part2 from Table_3 where id = @id",
new { id = textBox1.Text });
注意:如果数据实际上定义为bit
,那么您将需要.NET中的bool
/ Boolean
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.