【发布时间】:2022-01-20 09:14:19
【问题描述】:
我正在尝试从 sql 数据库中读取数据。当我运行代码时,它会在读取数据的位置出现错误。
“System.InvalidCastException:指定的强制转换无效。”
我得到一个错误。我研究了我的错误,但找不到适合我的解决方案。虽然我编写的查询文本在 ssms 中有效,但在代码中无效。
private void pbx_frame_MouseUp(object sender, MouseEventArgs e) //
{
//take cropped image to picture box of crooped images
try
{
string[] resim = lbx_raw_image.SelectedItem.ToString().Replace(':','.').Split('.');
string sorgu_sql = "Data Source=DESKTOP-OON7EET\\SQLEXPRESS;Initial Catalog=Target;Integrated Security=True;"; //sql bağlantısı kuruldu
//string query = "SELECT * FROM MP_Data$ WHERE time= '19.53.06'"; //'" + lbx_raw_image.SelectedItem.ToString() + "'"; //time=19.53.06 tek bir veriyi çağrır. muhtemelen yorum haline getirilen kısım olacaktı.
string query = "SELECT * FROM MP_DATA_15_mayıs_2019$ WHERE time='" + lbx_raw_image.SelectedItem.ToString() + "'"; //12.50.23
DB_islem db = new DB_islem(sorgu_sql, query); //
pic_info_from_MP = db.Raw_Image(pic_info_from_MP);
public Target Raw_Image(Target pic_info)
{
sql.Open();
sql_read = sql_command.ExecuteReader();
//while (sql_read.Read())
if (sql_read.Read())
{
pic_info.lat = sql_read.GetDouble(0);
pic_info.lon = sql_read.GetDouble(1);
pic_info.alt = sql_read.GetDouble(2);
pic_info.yaw = sql_read.GetDouble(3);
}
sql.Close();
return pic_info;
}
解决方案:
ALTER TABLE table1(name of table) ALTER COLUMN clmn1(name of column) float(datatype);
我使用上述查询确定了每一列的数据类型。帮我调用了所需的数据。
【问题讨论】:
-
如果 time = '12.50.23',为什么你在代码前面替换冒号,而不是在查询中?并参数化您的查询以确保安全性、性能和准确性
-
我猜这是你的 alt 值。 SSMS 可能会处理这个问题,但在 c# 中,double 被限制为 16 位,因此这个值有太多小数。尝试使用十进制类型。
-
请显示表定义
-
正如@LocEngineer 所说,alt 列中的值可能太长。此外,您可以在其他列上有更多有问题的值,因为您使用了 where 子句,我们看不到所有内容。
标签: c# sql ssms sqldatareader