Search code examples
vb.netoledbsqlclientoledbcommandoledbdatareader

Two Connections types in one method (SQL and OLEDB)


I have two connections types to be used in my app. One is SQL Server, using the SqlClient.Connection type. The other one uses the OleDb.Connection type.

The question is, when using a DataAdapter, DataReader, and Command, how can I use one reference for each with both connections?

As an example, I want to use a reader like this:

Dim MyReader As OleDb.OleDbDataReader 

to check my data with an OleDbConnection, and then use same reader to check data from the second SqlClient connection. That is, I want to do something like this (pseudocode):

Dim con 
Dim MyReader
con = oledb.connection
MyReader = mymethod(con)
con = sql.sqlclient.conection
MyReader = mymethod2(con)

How can I do this in real code?

I need help in how to declare data components for two different connection types inside the same method or function.


Solution

  • You should declare multiple variables. It's really not a big deal to do so.

    But, if you really want to do this (again: not the best idea) one thing you can keep in mind is these objects all inherit from a common set of types in the System.Data.Common namespace. So it possible to write code like this:

    Dim con As System.Data.Common.DbConnection = New OleDbConnection("connection string here")
    Dim cmd As System.Data.Common.DbCommand = New OleDbCommand("SELECT * ... ", con)
    
    con.Open()
    Dim rdr As System.Data.Common.DbDataReader = con.ExecuteReader()
    While rdr.Read()
        ' ...
    End While
    con.Close()
    
    con = New SqlClient.SqlConnection("connection string here")
    cmd = New SqlClient.SqlCommand("SELECT * ...", con)
    con.Open()
    rdr = cmd.ExecuteReader()
    While rdr.Read()
        ' ...
    End While
    

    But again: you really are better off using separate variables.