Teaching myself ado.net coming from dao vb background.
Searching assorted code examples I was able to write something to extract some data from the pubs database in sql. Now I am trying to modify it to fit my needs. Because I will be accessing the database quite often I want to avoid recreating my objects over and over (sqlconnection, sqldataadapter, dataset) and just create them once globally. But they seem designed to use their constructors to build them up in succession when it is time to use them. I was able to find a way around most of it but I am stuck on a couple spots.
- How can I connect the
SqlDataAdapterto theSqlConnectionoutside of it's constructor? - What is the syntax to reference a specific 'record' in the results without iterating through the results with a FOR EACH.
Here is my code (This code is just to learn how to use it. It is not intended to be a practical application)
Imports System.Data.SqlClient
Public Class SqlLink
Dim conn As New SqlConnection
Dim da As New SqlDataAdapter
Dim ds As New DataSet
Public Function Connect(ByVal sConnString As String) As Integer
'attempts to connect to database, returns error code
Try
conn.ConnectionString = sConnString
conn.Open()
Return 0
Catch ex As Exception
MsgBox(Err.Description)
Return Err.Number
End Try
End Function
Public Sub exampleroutine()
Dim TempRow As DataRow
'DO NOT WANT Dim da as new sqlDataAdapter("some query", conn)
'I DO NOT WANT TO DIM THE da HERE. I WANT IT DIM'D ONCE GLOBALLY
'HOW CAN I TIE THE da TO THE conn HERE OUTSIDE OF IT'S CONSTRUCTOR
da.SelectCommand.CommandText = "SELECT au_fname FROM authors where au_fname like '%ann%'"
da.Fill(ds)
For Each TempRow In ds.Tables(0).Rows
MsgBox(TempRow("au_fname"))
Next
da.SelectCommand.CommandText = "SELECT au_fname FROM authors where au_fname like '%reg%'"
da.Fill(ds)
'HOW TO GET A SPECIFIC 'RECORD' WITHOUT ITERATING THROUGH WITH A FOR EACH
'If ds.Tables(0).Rows.Count > 0 Then ???
End Sub
End Class
======================================================
I worked out a solution but I don't know if anyone wants to, or should, follow it in light of the comments but.. just for closure, this is what I did to resolve this.
In the Connect function, right after conn.Open I added
da = New SqlDataAdapter(False, conn)
This created a reusable global instance of the data adapter.