C#报invalid column name

C#sql 数据库放在程序中报invalid column name ‘NaN’,但是放在单一的代码中不会报错。

 public void Value_Library(string volatage, float load, string name, float min, float measure, float max, int id)
        {
            string result = string.Empty;
            if (min < measure && max > measure)
            {
                result = "PASS";
            }
            else
            {
                result = "FAIL";
            }
            SqlCommand sql = new SqlCommand($"select count(*) from My_table where id = '{id}'", conn);
            int num = (int)sql.ExecuteScalar();
            if (num == 1)
            {

                SqlCommand sql2 = new SqlCommand($"update My_table set Volatage = '{volatage}',Load = {load}, Name = '{name}', Min = {min}, Measure = {measure}, Max = {max}, Result = '{result}' where id = '{id}'", conn);
                if (sql2.ExecuteNonQuery() > 0)
                {  }
            }
            else
            {
                SqlCommand sql1 = new SqlCommand($"insert into My_table(Volatage,Load,Name,Min,Measure,Max,Result) Values('" + volatage + "'," + load + " ,'" + name + " '," + min + ", " + measure + ", " + max + ", '" + result + "')", conn);
                if (sql1.ExecuteNonQuery() > 0)
                { }
            }
        }

打印日志:

string volatage, float load, string name, float min, float measure, float max, int id

打印这些参数看是否有值

可能是由于程序中的某些代码使用了"NaN"(非数值)作为列名或列值

推荐你使用 SqlParameter 来进行参数传递,不用字符串拼接方式

1 是这样不容易被注入攻击

2 是传参方式,避免字符串拼接时格式错误,无需额外处理比如单引号之类的东西

在你的代码中,"NaN" 可能是由于 min 或 max 参数中包含了非数值的值(例如空字符串或 null)导致的。

如果你的数据表中的列的数据类型为 float 类型,那么它不支持插入或更新非数值的值。因此,当你尝试将非数值的值插入或更新到该列时,就会报 "invalid column name ‘NaN’" 的错误。

你可以在调用 Value_Library 方法之前,确保 min 和 max 参数包含数值类型的值。例如,你可以在方法调用前添加以下代码,将空字符串或 null 转换为默认值 0:

if (string.IsNullOrEmpty(min.ToString())) min = 0;
if (string.IsNullOrEmpty(max.ToString())) max = 0;

或者,你可以使用 float.TryParse 方法来确保这些值为数值类型:

float minVal = 0;
float maxVal = 0;
float.TryParse(min, out minVal);
float.TryParse(max, out maxVal);

望采纳😊