2011-06-15 70 views
0

每当我有问题与VB

Dim catID as integer 

查询SQL Server和我用这个在这样的查询:

cmd.CommandText = "select * from categories where parentid='" + catID + "'" 

我得到:

从字符串转换select * from categories where p键入Double无效。

这是为什么?
sql中的parentid数据类型为integer

+0

试试这个:cmd.CommandText = “SELECT * FROM其中的parentid =类别 '” + catID.ToString()+ “'” 此外,仅仅是一个想法:要指定CATID对于parentid ...您的上述查询是否在SQL Server Management Studio中运行? – DoomerDGR8 2011-06-15 22:44:24

+4

请始终使用参数化查询,绝不要使用字符串连接。 – 2011-06-15 22:47:52

+0

此错误消息来自哪里?我怀疑它是SQL Server,因为Double数据类型被称为Float。 – Jeff 2011-06-15 22:53:50

回答

1

尝试

cmd.CommandText = string.Format("select * from categories where parentid='{0}'", catID) 

如果parentid是在你的数据库的数字字段,那么你就需要

cmd.CommandText = string.Format("select * from categories where parentid={0}", catID) 
+0

非常感谢你:)我几乎所有的东西都试过了,感到非常失望。 – ConfusedCoder 2011-06-15 23:02:31

1

只是删除单引号:

cmd.CommandText = "select * from categories where parentid=" + catID.ToString() 
0

错误告诉你它不能在您的catID值中添加“SELECT * ...”。 '+'运算符试图将“SELECT * ...”转换为数字,因此它可以对它进行数学运算,但它不能,所以它抛出了错误。

很多人试图用'+'来表示字符串连接。这不是最好的做法,因为只有当双方都是字符串时,“+”才会连接。但是,如果它发现一个数字(就像你的情况一样,使用catID),那么它会尝试做数学而不是concat。

最好的做法,只养成从不使用'+'串接字符串的习惯;请始终使用'&'。这样你就不必考虑它了。

即:

1+1 = 2 
1+A = error 
1&1 = 11 
1&A = 1A 
+0

顺便说一句 - 关于参数化你的查询的其他意见很重要。就注射风险而言,可能会危险,就像你这样做。 – Chains 2011-06-15 23:36:42

+0

它的一个内部应用程序,所以不用担心:)顺便说一句,提示是伟大的,我会记住它现在:) – ConfusedCoder 2011-06-16 00:22:54