Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Retrieve one field/one record from DB – how? 1

Status
Not open for further replies.

Andrzejek

Programmer
Jan 10, 2006
8,565
US
I am (kind of) new to VB.NET
I know I can request information from data base and keep it in a table in a dataset.
I also know I can use a data reader if I need to have read-only forward-only access to some data.

What can I (should I) use if I only want to request one field/one record from my data base?
Let say I just want to get the Count of how many records are in the data base according to some criteria:
[tt]
Select Count(*) As How_Many
From SomeTable
Where …
[/tt]
I know I can use a table in a data set (that would be an over kill, I would guess), or even a data reader (which would work just fine). But I think I saw somewhere there is another way to get this little piece of information in VB.NET.

I don’t even know what to Google, that’s why I ask here.


Have fun.

---- Andy
 
Set up a Command object and use the ExecuteScalar method, which returns a single value.

Dim cmd As SqlCommand 'or OleDbCommand, or whatever

Dim Conn As New SqlConnection("connection string")

Dim SqlStr As String = "Select Count(*) As How_Many From SomeTable Where …"

cmd = New SqlCommand(SqlStr, Conn)

Dim TableCount as Integer

If Not IsDbNull(cmd.ExecuteScalar) Then
RecordCount = cmd.ExecuteScalar()
EndIf

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top