简体   繁体   English

如何将值从数据库返回到变量

[英]How to return value from database into a variable

static float ExecuteQueryWithResult_fl(SqlConnection connection, string query)
        {
            using (SqlCommand command = new SqlCommand(query, connection))
            {
                float prev_val = ((float)command.ExecuteScalar());
                return prev_val;
            }
        }

Call : 致电:

float f = ExecuteQueryWithResult_fl(connection, prev_status);

Iam using this in a client application that communicates with server , whenever this line is about to be executed : The connection breaks ! 每当要执行此行时,我都会在与服务器进行通信的客户端应用程序中使用此方法:连接中断! No error comes out . 没有错误出现。 What may be the problem ?? 可能是什么问题?

public static void update_data_base(string type_id,int station, int ioa, byte by_val, float fl, uint bcr, bool is_float, bool is_bcr_iti,byte ov, byte bl, byte sb,byte nt, byte iv, byte seq, byte cy, byte ca)
        {
            string connectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=C:\\Users\\Ahmed Aek Ben Jemia\\Desktop\\newest\\command combo\\1\\iec104_master_slave_rtu\\Combo_1.mdf;Integrated Security=True";
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                string updateCommand = null,updateCommand1=null;
                connection.Open();
                ConnectionState state = connection.State;

                float f = 0;

                string prev_status = string.Format("SELECT STATUS FROM ") + type_id + string.Format("_Table WHERE ASDU={0} AND IOA={1}", station, ioa);
                    try
                    {
                    f = ExecuteQueryWithResult_fl(connection, prev_status);
                    }
                    catch (Exception e)
                    {
                        SetText2(e.ToString());
                    }                  
            }

        }

Error : System.InvalidCastException: Specified cast is not valid 错误:System.InvalidCastException:指定的转换无效

PS : I can get string & byte values from database , this only happens with float and int. PS:我可以从数据库中获取字符串和字节值,这仅在float和int时发生。

What you have looks ... usable (although I'd be very concerned about how you are passing in parameters); 您所看到的...可用(尽管我会非常担心您如何传递参数); your code works fine when called like this: 这样调用时,您的代码可以正常工作:

public static void Main()
{
    float f;
    using(var conn = new SqlConnection("Server=.;Integrated Security=SSPI"))
    {
        conn.Open();
        f = ExecuteQueryWithResult_fl(conn, "select cast(1.23 as float(24))");
    }
    Console.WriteLine(f); // 1.23
}

So the problem isn't the method you've shown (by itself). 因此,问题不在于您所展示的方法 (本身)。 To understand what is happening, you should use a debugger and see what happens. 要了解发生了什么,您应该使用调试器并查看发生了什么。 My guess would be one of: 我的猜测是以下之一:

  • an invalid cast (the difference between float in C# and the SQL Server data types) 无效的转换(C#中的float与SQL Server数据类型之间的差异)
  • invalid SQL from concatenating values into the query (a very very bad thing to do) 将值连接到查询中导致无效的SQL(要做的事情非常非常糟糕)

combined with calling code that is swallowing an Exception without displaying it to you. 与吞下Exception而不显示给您的调用代码结合在一起。 The debugger will tell you, once you have a break-point at the location that isn't working. 一旦您在无法使用的位置设置了断点,调试器就会告诉您。

Try the following and ensure your that your connection is open already. 请尝试以下操作,并确保您的连接已打开。

static float ExecuteQueryWithResult_fl(SqlConnection connection, string query)   {
            try {        
                using (SqlCommand command = new SqlCommand(query, connection))
                {
                    var prev_val = command.ExecuteScalar().ToString() == null ? default(float) : float.Parse(command.ExecuteScalar().ToString());;
                    return prev_val;
                }
            }

           catch (Exception x) 
           { 
                Console.WriteLine("Error fetching due to {0}", x.Message); 
                return default(float);
           }
     }

Update: Replace your query with: 更新:将查询替换为:

string prev_status = string.Format("SELECT cast(STATUS as float) prev_status FROM {0}_Table WHERE ASDU={1} AND IOA={2}",type_id, station, ioa);

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

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