How to Access VB Select Query
Learning how to access a query using Microsoft Visual Basic.NET (VB.NET) can save you time if you need to display data from a database. A query is used to retrieve results from a database table. In a few steps you can connect to a database, build a select query and display the contents of the first field through a data set.
Instructions
-
-
1
Start Microsoft Visual Basic Express and click "New Project..." on the left pane of your screen. Double-click "Console Application." Press "Ctrl" and "A" then press "Delete" to remove existing code.
-
2
Copy and paste the following code to your "Module1.vb" module. The code will make the database connection and query a table through a select query. The query results for the first field will be displayed in the output window.
Imports System.Data.Odbc.OdbcConnection
Module Module1
Sub Main()
Dim xCntr As Integer
Dim dbConn As Odbc.OdbcConnection
dbConn = New Odbc.OdbcConnection("DSN=TRA3")
dbConn.Open()
Dim da As New Odbc.OdbcDataAdapter("SELECT UNIT_DATA.* FROM UNIT_DATA;", dbConn)
Dim ds As New Data.DataSet
da.Fill(ds)
For xCntr = 0 To ds.Tables(0).Rows.Count - 1
Console.Write(ds.Tables(0).Rows(xCntr).Item(0))
Next
dbConn.Close()
dbConn.Dispose()
dbConn = Nothing
End Sub
End Module
-
-
3
Edit the following line of code and type the name of your DSN.
dbConn = New Odbc.OdbcConnection("DSN=TRA3")
Edit the following line of code and type the select query you want to run.
Dim da As New Odbc.OdbcDataAdapter("SELECT UNIT_DATA.* FROM UNIT_DATA;", dbConn)
-
4
Press "F5" to run your program.
-
1
References
- Photo Credit Paul Cooklin/Brand X Pictures/Getty Images