我试图读取数据从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;
}
首先,您应该仅使用参数执行查询。其次,我们不知道您的表模式--请显示它。
但最可能的问题是如何存储该值。GetDouble不进行任何转换,因此您的数据应该已经保存为double。
更重要的是,全球化可能存在问题。你应该做的是:
using System.Globalization;
//...
double result = double.NaN;
if(!sql_read.IsDbNull(0))
{
string s = sql_read.GetString(0);
result = Convert.ToDouble(s, CultureInfo.InvariantCulture);
}