473,473 Members | 2,236 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

reading values from database

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
Nov 21 '05 #1
7 1677
I do something like this. Modify CommandType and CommandText for your query
(I use stored procedures here).

' Our data reader

Dim DataReader As SqlDataReader

' Result

Dim Result As Boolean = False

' Do sommit

Try

Dim Command As New SqlCommand

' Setup the command object

Command.Connection = m_Connection
Command.CommandText = "proc_SomeStoredProcedure_or_select_text"
Command.CommandType = CommandType.StoredProcedure

' Execute the reader

DataReader = Command.ExecuteReader()

' Now iterate the result set

If DataReader.HasRows Then

While DataReader.Read() ' ie. for each record returned

' Get a value...

Dim aValue, aNotherValue as integer

aValue = DataReader.GetInt32(0)
aNotherValue = DataReader.GetInt32(1)

End While

End If

' Success

Result = True

Catch Ex As Exception

' Failed

Result = False

Finally

' Close reader

If Not DataReader Is Nothing Then

DataReader.Close()

End If

End Try

Return Result

"simon" <si*********@stud-moderna.si> wrote in message
news:uP**************@TK2MSFTNGP14.phx.gbl...
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
Nov 21 '05 #2
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/de...classtopic.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/de...ml/daab-rm.asp

--
W.G. Ryan, MVP

www.tibasolutions.com | www.devbuzz.com | www.knowdotnet.com
"simon" <si*********@stud-moderna.si> wrote in message news:uP**************@TK2MSFTNGP14.phx.gbl...
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
Nov 21 '05 #3
Simon,

There are not much "best" ways in VBNet and certainly not for such a wide question as yours.

It depends why you want to read something, do you by instance want to read only one value, than the executescalar is a way to go however not with the select as you use.

http://msdn.microsoft.com/library/de...calartopic.asp

I think a good thing to do for you is reading some books, mostly advices in the dotNet newsgroups are the books for Adonet from Davis Sceppa or William(Bill) Vaughn

And when you tell us something more what you want to archive, than maybe we can help you in the right direction.

I hope this helps a anyway?

Cor
Nov 21 '05 #4
Robin:

Just to add a quick tidbit - closing the Connection is ostensibly one of the
more important issues you need to address. You can specify CloseCOnnection
in the CommandBehavior Enumeration of ExecuteReader which will handle this
for you whenever you close the reader but it's a must unless you want to
risk some serious performance hits. I'd also avoid trapping
System.Exception here. A StackOVerflow isn't the same things as a
Connection Timeout so I'd trap Connection.Open() individually as well as
executeReader and wrap them in SqlException, OleDbException etc

--
W.G. Ryan, MVP

www.tibasolutions.com | www.devbuzz.com | www.knowdotnet.com
"Robin Tucker" <id*************************@reallyidont.com> wrote in
message news:cj******************@news.demon.co.uk...
I do something like this. Modify CommandType and CommandText for your query (I use stored procedures here).

' Our data reader

Dim DataReader As SqlDataReader

' Result

Dim Result As Boolean = False

' Do sommit

Try

Dim Command As New SqlCommand

' Setup the command object

Command.Connection = m_Connection
Command.CommandText = "proc_SomeStoredProcedure_or_select_text"
Command.CommandType = CommandType.StoredProcedure

' Execute the reader

DataReader = Command.ExecuteReader()

' Now iterate the result set

If DataReader.HasRows Then

While DataReader.Read() ' ie. for each record returned

' Get a value...

Dim aValue, aNotherValue as integer

aValue = DataReader.GetInt32(0)
aNotherValue = DataReader.GetInt32(1)

End While

End If

' Success

Result = True

Catch Ex As Exception

' Failed

Result = False

Finally

' Close reader

If Not DataReader Is Nothing Then

DataReader.Close()

End If

End Try

Return Result

"simon" <si*********@stud-moderna.si> wrote in message
news:uP**************@TK2MSFTNGP14.phx.gbl...
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

Nov 21 '05 #5
Ahh yes. My connection gets closed a little later, ie. like this (not made
clear in my original post)

Dim theObject as MyDataBaseClass()

Try

' Create it

theDBObject = new MyDataBaseClass ( s_ConnectionString )

' Execute a method...

Result = theDBObject.FetchMyImagesFromDataBase()
If Not Result Then
Throw New Exception ( "Something screwed up" )
End If

' and another one

Result = theDBObject.DoAnotherThingBeforeClosing()

...
...

Catch Ex as Exception

Finally

If not theDBObject is Nothing Then
theDBObject.Close()
End If

End Try

"W.G. Ryan eMVP" <Wi*********@gmail.com> wrote in message
news:%2***************@TK2MSFTNGP11.phx.gbl...
Robin:

Just to add a quick tidbit - closing the Connection is ostensibly one of
the
more important issues you need to address. You can specify
CloseCOnnection
in the CommandBehavior Enumeration of ExecuteReader which will handle this
for you whenever you close the reader but it's a must unless you want to
risk some serious performance hits. I'd also avoid trapping
System.Exception here. A StackOVerflow isn't the same things as a
Connection Timeout so I'd trap Connection.Open() individually as well as
executeReader and wrap them in SqlException, OleDbException etc

--
W.G. Ryan, MVP

www.tibasolutions.com | www.devbuzz.com | www.knowdotnet.com
"Robin Tucker" <id*************************@reallyidont.com> wrote in
message news:cj******************@news.demon.co.uk...
I do something like this. Modify CommandType and CommandText for your

query
(I use stored procedures here).

' Our data reader

Dim DataReader As SqlDataReader

' Result

Dim Result As Boolean = False

' Do sommit

Try

Dim Command As New SqlCommand

' Setup the command object

Command.Connection = m_Connection
Command.CommandText = "proc_SomeStoredProcedure_or_select_text"
Command.CommandType = CommandType.StoredProcedure

' Execute the reader

DataReader = Command.ExecuteReader()

' Now iterate the result set

If DataReader.HasRows Then

While DataReader.Read() ' ie. for each record returned

' Get a value...

Dim aValue, aNotherValue as integer

aValue = DataReader.GetInt32(0)
aNotherValue = DataReader.GetInt32(1)

End While

End If

' Success

Result = True

Catch Ex As Exception

' Failed

Result = False

Finally

' Close reader

If Not DataReader Is Nothing Then

DataReader.Close()

End If

End Try

Return Result

"simon" <si*********@stud-moderna.si> wrote in message
news:uP**************@TK2MSFTNGP14.phx.gbl...
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


Nov 21 '05 #6
Hmmmm. You have a point about trapping Timeout. This is important in
applications (unlike mine) where you could indeed get a long response time
from the server. In my application (which is single user), I assume a
timeout means that SQL server is broken and so treat it as a "failure" like
every other exception.

"W.G. Ryan eMVP" <Wi*********@gmail.com> wrote in message
news:%2***************@TK2MSFTNGP11.phx.gbl...
Robin:

Just to add a quick tidbit - closing the Connection is ostensibly one of
the
more important issues you need to address. You can specify
CloseCOnnection
in the CommandBehavior Enumeration of ExecuteReader which will handle this
for you whenever you close the reader but it's a must unless you want to
risk some serious performance hits. I'd also avoid trapping
System.Exception here. A StackOVerflow isn't the same things as a
Connection Timeout so I'd trap Connection.Open() individually as well as
executeReader and wrap them in SqlException, OleDbException etc

--
W.G. Ryan, MVP

www.tibasolutions.com | www.devbuzz.com | www.knowdotnet.com
"Robin Tucker" <id*************************@reallyidont.com> wrote in
message news:cj******************@news.demon.co.uk...
I do something like this. Modify CommandType and CommandText for your

query
(I use stored procedures here).

' Our data reader

Dim DataReader As SqlDataReader

' Result

Dim Result As Boolean = False

' Do sommit

Try

Dim Command As New SqlCommand

' Setup the command object

Command.Connection = m_Connection
Command.CommandText = "proc_SomeStoredProcedure_or_select_text"
Command.CommandType = CommandType.StoredProcedure

' Execute the reader

DataReader = Command.ExecuteReader()

' Now iterate the result set

If DataReader.HasRows Then

While DataReader.Read() ' ie. for each record returned

' Get a value...

Dim aValue, aNotherValue as integer

aValue = DataReader.GetInt32(0)
aNotherValue = DataReader.GetInt32(1)

End While

End If

' Success

Result = True

Catch Ex As Exception

' Failed

Result = False

Finally

' Close reader

If Not DataReader Is Nothing Then

DataReader.Close()

End If

End Try

Return Result

"simon" <si*********@stud-moderna.si> wrote in message
news:uP**************@TK2MSFTNGP14.phx.gbl...
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


Nov 21 '05 #7
I figured as much. Forgetting to close connections or have them in a using
block or finally statement is the source of a lot of drama so I figured I'd
mention it.

--
W.G. Ryan, MVP

www.tibasolutions.com | www.devbuzz.com | www.knowdotnet.com
"Robin Tucker" <id*************************@reallyidont.com> wrote in
message news:cj*******************@news.demon.co.uk...
Ahh yes. My connection gets closed a little later, ie. like this (not made clear in my original post)

Dim theObject as MyDataBaseClass()

Try

' Create it

theDBObject = new MyDataBaseClass ( s_ConnectionString )

' Execute a method...

Result = theDBObject.FetchMyImagesFromDataBase()
If Not Result Then
Throw New Exception ( "Something screwed up" )
End If

' and another one

Result = theDBObject.DoAnotherThingBeforeClosing()

...
...

Catch Ex as Exception

Finally

If not theDBObject is Nothing Then
theDBObject.Close()
End If

End Try

"W.G. Ryan eMVP" <Wi*********@gmail.com> wrote in message
news:%2***************@TK2MSFTNGP11.phx.gbl...
Robin:

Just to add a quick tidbit - closing the Connection is ostensibly one of
the
more important issues you need to address. You can specify
CloseCOnnection
in the CommandBehavior Enumeration of ExecuteReader which will handle this for you whenever you close the reader but it's a must unless you want to
risk some serious performance hits. I'd also avoid trapping
System.Exception here. A StackOVerflow isn't the same things as a
Connection Timeout so I'd trap Connection.Open() individually as well as
executeReader and wrap them in SqlException, OleDbException etc

--
W.G. Ryan, MVP

www.tibasolutions.com | www.devbuzz.com | www.knowdotnet.com
"Robin Tucker" <id*************************@reallyidont.com> wrote in
message news:cj******************@news.demon.co.uk...
I do something like this. Modify CommandType and CommandText for your

query
(I use stored procedures here).

' Our data reader

Dim DataReader As SqlDataReader

' Result

Dim Result As Boolean = False

' Do sommit

Try

Dim Command As New SqlCommand

' Setup the command object

Command.Connection = m_Connection
Command.CommandText = "proc_SomeStoredProcedure_or_select_text"
Command.CommandType = CommandType.StoredProcedure

' Execute the reader

DataReader = Command.ExecuteReader()

' Now iterate the result set

If DataReader.HasRows Then

While DataReader.Read() ' ie. for each record returned

' Get a value...

Dim aValue, aNotherValue as integer

aValue = DataReader.GetInt32(0)
aNotherValue = DataReader.GetInt32(1)

End While

End If

' Success

Result = True

Catch Ex As Exception

' Failed

Result = False

Finally

' Close reader

If Not DataReader Is Nothing Then

DataReader.Close()

End If

End Try

Return Result

"simon" <si*********@stud-moderna.si> wrote in message
news:uP**************@TK2MSFTNGP14.phx.gbl...
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



Nov 21 '05 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: John | last post by:
I have over 5000 thumbnail pictures of size 5kb each. I would like to able to load all 5000 pictures and view 50 per page using mysql_data_seek(). I would like to know what are the advantages and...
2
by: Dariusz | last post by:
Below is part of a code I have for a database. While the database table is created correctly (if it doesn't exist), and data is input correctly into the database when executed, I have a problem...
1
by: Sunil Pathi | last post by:
Thanks in Advance I have a XML file which is read from a .aspx page. I need to read through all the elements, find the values of them and pass them on to the stored procedure which updates the...
6
by: Paul | last post by:
I was wondering if anyone has had an issue where using vba code to read an excel file and import the data into an access table some records are not imported from the excel file. It seems looking at...
4
by: Andy | last post by:
Hello All: I have a field in the database that is an Image. I have no idea how the data is stored in here (Image, compressed, encrypted, plain text, etc). I am trying to write the contents to...
1
by: Bijoy Naick | last post by:
I have a form with mutiple text fields, all of similar nature.. for example: userName1, location1 userName2, location2 .. .. .. userName10, location10
1
by: vadarv | last post by:
Hia! I'm a total amateur to VBS but need help on a VBS script. This is used in a HMI system from Siemens called WinCC, used for process viewing and control. What I need to is to write to a table...
2
by: Derik | last post by:
I've got a XML file I read using a file_get_contents and turn into a simpleXML node every time index.php loads. I suspect this is causing a noticeable lag in my page-execution time. (Or the...
6
by: jcasique.torres | last post by:
Hi everyboy. I trying to create a C promang in an AIX System to read JPG files but when it read just the first 4 bytes when it found a DLE character (^P) doesn't read anymore. I using fread...
4
by: ducttape | last post by:
Hi, I have been trying for several days to read XML files into my program. I have been following several good tutorials on the internet, but I am struggling because the particular XML files that I...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.