# VB2005 - How do I display database field in a label?



## Akumos (May 10, 2010)

Hi

Sorry for all the questions, I appreciate everyone who has read and attempted to help me over the last few days.

I have a label on a form and want to use it to display a field from a record in the database....

This is all I reallty have so far:

 Dim titleOne As String

        Dim sqlString As String = "SELECT title FROM move WHERE boxOffice = 1"

        Dim dbPath = "C:\movies.mdb"

        Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" & dbPath



THANKS all


----------



## Rusel (May 10, 2010)

```
Dim con As OleDbConnection = New OleDbConnection(connectionString)
            Dim cmd As OleDbCommand = New OleDbCommand(sqlString, con)

            con.Open()
	 Dim reader As OleDbDataReader = cmd.ExecuteReader()

            While reader.Read()
		myLabel.Text = reader.GetValue(0).ToString()
            End While

            reader.Close()
            con.Close()
```
*EDIT: * Fixed


----------



## Akumos (May 10, 2010)

Thanks for the reply Rusel... getting an error on the dbr part.... (drb not declared)


----------



## Akumos (May 10, 2010)

Cheers Rusel! Working GREAT!!!!

Thanks alot!


----------



## Kreij (May 10, 2010)

If you know that the query result will always be a single record and unique, you could also use "ExecuteScalar".

But this only returns one value (column) from the DB.


----------



## Akumos (May 10, 2010)

Thanks for the info Kreij.. got it workin now so better not play with it too much!


----------



## Kreij (May 11, 2010)

Just so you know, if you lnow that only one value needs to be returned, ExecuteScalar is faster and the response message payload is smaller when compared to what is returned by ExecuteReader.

Here's an example of using it. This will return the PK of the record on an insert.

```
Dim movieTitle As String = "New Movie Name
Dim NewMovieID As Int32 = 0
Dim sQuery As String = "INSERT INTO movie (movieTitle) VALUES(' + movieTitle + 
     "'); SELECT CAST(SCOPE_IDENTITY() is Int);"

Using con As New OleDbConnection(connectionString)
    Dim cmd As OleDbCommand = New OleDbCommand(sQuery, con)
    Try
        con.Open()
        NewMovieID = Convert.ToInt32(con.ExecuteScalar())
     catch ex As Exception
         Console.Writeln(ex.Message);
     End Try
End Using
```

Notice also that it is good practice to wrap your connections in a "Using" block.
When the block completes it will automatically close the connection and prevent problems if you forget to do that.


----------

