转换varchar值时转换失败

Kev*_*sen 0 c# sql parameters error-handling type-conversion

当我尝试运行它时,它给我以下错误消息:

将varchar值'category_id'转换为数据类型int时转换失败.

这是我的SQL和参数代码,我认为它应该可以工作,但事实并非如此.

mycmd.CommandText="SELECT * FROM categories WHERE @db_property = @property_id"; 

// This contains a string "category_id", which is correct.
mycmd.Parameters.Add("@db_property", SqlDbType.VarChar).Value=db_property_field; 

// This contains an Int, referring to the category_id in database. As of now, this is 1
mycmd.Parameters.Add("@property_id", SqlDbType.Int).Value=property_id; 
Run Code Online (Sandbox Code Playgroud)

在我完成这段代码之后,我通过Reader运行它,这就是我收到上面的错误消息的地方.一直问老师,我班上优秀的学生,没有人能找到问题所在的线索.

Den*_*nko 6

您不应该将字段名称添加为参数.尝试更改脚本以包含实际字段ID:

mycmd.CommandText = "SELECT * FROM categories WHERE category_id = @property_id";
mycmd.Parameters.Add("@property_id", SqlDbType.Int).Value = property_id;
Run Code Online (Sandbox Code Playgroud)