Problem with querying sql server from vb

守給你的承諾、 提交于 2020-01-17 07:42:10

问题


Whenever I have

Dim catID as integer

And I use this in a query like this:

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

I get:

Conversion from string select * from categories where p to type Double is not valid.

Why is it so?
The parentid datatype in sql is integer.


回答1:


Try

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

if parentid is a numeric field in your database then you'll need

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



回答2:


Just remove single quotes:

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



回答3:


The error was telling you that it couldn't add "SELECT *..." with your catID value. The '+' operator tried to convert "SELECT *..." into a number so it could do math on it, but it couldn't, so it threw the error.

A lot of people try to use '+' for string concatenation. This is not the best practice because '+' will only concatenate when both sides are strings. But if it finds a number on one side (as in your case, with catID), then it will try to do math instead of concat.

Best practice to just make a habit to never use '+' to concat strings; always use '&' instead. That way you don't have to think about it.

I.e.:

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


来源:https://stackoverflow.com/questions/6365294/problem-with-querying-sql-server-from-vb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!