static float ExecuteQueryWithResult_fl(SqlConnection connection, string query)
{
using (SqlCommand command = new SqlCommand(query, connection))
{
float prev_val = ((float)command.ExecuteScalar());
return prev_val;
}
}
致电:
float f = ExecuteQueryWithResult_fl(connection, prev_status);
Iam在与服务器通信的客户端应用程序中使用它,每当要执行此行时:连接中断!没有错误出现。可能是什么问题??
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());
}
}
}
错误:System.InvalidCastException:指定的强制转换无效
PS:我可以得到字符串&来自数据库的字节值,这只发生在float和int。
答案 0 :(得分:1)
你看起来有什么......可用(虽然我非常关心你如何传递参数);你的代码在这样调用时工作正常:
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
}
所以问题不是您展示的方法(单独)。要了解发生了什么,您应该使用调试器,看看会发生什么。我的猜测是:
float
与SQL Server数据类型之间的差异)与正在吞咽Exception
的调用代码相结合而不向您展示。一旦在不工作的位置有断点,调试器就会告诉你。
答案 1 :(得分:1)
请尝试以下操作并确保您的连接已打开。
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);
}
}
<强>更新强> 用以下内容替换您的查询:
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);