Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 612
  • Last Modified:

Open sql database vb.net

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.

Thanks.
0
TheChos
Asked:
TheChos
  • 2
  • 2
1 Solution
 
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)

cn.Open()

Dim dr As New SqlDataReader = cmd.ExecuteReader()

While dr.Read()

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

End While

cn.Close()

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)
0
 
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"?
0
 
Carl TawnSystems 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

0
 
TheChosAuthor Commented:
Worked Great!  Thank you very much.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now