If you need multiple values, then ExecuteScalar isn't the way to go. First off though, I'd cast the return value instead of using object - so if you were expecting an Integer value, I'd use
Dim returnValue as System.Int32= CType(cmd.ExecuteScalar, System.Int32)
For this one though you can use a DataReader ie Dim dr as SqlDataReader
dr = cmd.ExecuteReader
'Assuming you know that you will only have one row back you can use the SingleResult enumeration
http://msdn.microsoft.com/library/d.../frlrfsystemdatacommandbehaviorclasstopic.asp
If dr.Read Then
Dim firstValue as System.String = dr.GetString(0) 'username
Dim secondValue as System.Int32 = dr.String(1)'userCountry
etc ( you can also use GetValue which is a little cleaner. ALso, make sure to check for DBNull values or you'll get a null reference exception.
End If
Two other things: 1) ALWAYS use a Try /Catch Finally on when using SqlConnection. Angel Saenz-Badillos describes why this is so critical here
http://weblogs.asp.net/angelsb/
2) Don't use concatenated SQL Like That - use Parameterized queries instead
http://www.knowdotnet.com/articles/dynamisql.html
http://www.knowdotnet.com/articles/storedprocsvb.html
It works the same whether you are using Stored Procedures or not so use them instead - Microsoft's Data Access Application Block is also a wonderful resource for stuff like this
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/daab-rm.asp
--
W.G. Ryan, MVP
www.tibasolutions.com |
www.devbuzz.com |
www.knowdotnet.com
What is the best way to read the values from the datatbase.
I have sql="SELECT userName, userCountry, userVisit from users where userID=2"
Create a command object?
Dim oCmd As SqlCommand
oCmd = New SqlCommand(sql, Connection)
object = oCmd.ExecuteScalar()
oCmd.Connection.Close()
How can I read the values from this?
userName=object.fields(0).Value ' or something like that
userCountry=...
userVisit=....
Thank you,
Simon