Problem with querying sql server from vb

前端 未结 3 1910
花落未央
花落未央 2021-01-27 22:31

Whenever I have

Dim catID as integer

And I use this in a query like this:

cmd.CommandText = \"select * from categories where p         


        
相关标签:
3条回答
  • 2021-01-27 22:48

    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)
    
    0 讨论(0)
  • 2021-01-27 22:50

    Just remove single quotes:

    cmd.CommandText = "select * from categories where parentid=" + catID.ToString()
    
    0 讨论(0)
  • 2021-01-27 22:57

    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
    
    0 讨论(0)
提交回复
热议问题