【发布时间】:2013-02-18 10:51:54
【问题描述】:
当我尝试运行它时,它给了我以下错误消息:
将 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;
浏览完这段代码后,我通过阅读器运行它,这就是我收到上述错误消息的地方。一直问老师,还有我班的优秀学生,没人能找到线索,问题出在哪里。
【问题讨论】:
-
嗯,它正在尝试将文字字符串
category_id转换为整数值,这当然会失败。你能把相关代码贴在实际发生错误的那一行吗? -
它在我的阅读器执行行运行时发生。
-
db_property_field 是否包含“1”?
-
它不是试图将
1转换为int,而是值category_id(作为varchar)。我认为 Denys 的回答应该可以解决您的问题。
标签: c# sql parameters error-handling type-conversion