Open sql database

I'm trying to get a grasp of how to perform basic database functions within VB.Net.  Can someone please provide a simple example of how to:
  Open a SQL database
  Perform a simple "SELECT *" query
  Loop through the result set one record at a time
  Perform a conditional on a datafield  (e.g.: IF "datafield" = 1 THEN)
  Close the database

Generic code examples would work fine.

Also, which project references would I need to include in my VB.Net app.

Who is Participating?
Carl TawnConnect With a Mentor Systems and Integration DeveloperCommented:
The DataReader exposes a method called GetOrdinal() which return the index of a column from its name. You can build that into your code to get fields by name:
     If dr.GetInt32(dr.GetOrdinal("SomeColumnName")) = 1 Then
         '// do something
     End If

Open in new window

Carl TawnSystems and Integration DeveloperCommented:
In very simple terms you would be looking at something like the following:
Dim cn As New SqlConnection("Your connection string")
Dim cmd As New SqlCommand("SELECT Something FROM SomeTable", cn)


Dim dr As New SqlDataReader = cmd.ExecuteReader()

While dr.Read()

     If dr.GetInteger(0) = 1 Then
         '// do something
     End If

End While


Open in new window

Note: Written from memory so may contain syntax errors :)

P.S. This uses the System.Data.SqlClient namespace and the System.Data assembly (which should be referenced in the project by default)
TheChosAuthor Commented:
All works great except that I'm having a little difficulty accessing the fields by name.  Could you send me an example of how to retrieve the value of a field named "ExampleField"?
TheChosAuthor Commented:
Worked Great!  Thank you very much.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.