How do you create an ADODB disconnected recordset in a VB.NET Windows application?

Matt Hamsmith picture Matt Hamsmith · Sep 2, 2011 · Viewed 7.5k times · Source

I'm using an OLEDB connection to a Sybase database, with ADODB.dll file version 7.10.6070.0 (which comes from the Sybase 12.5 package). I need to be able to open a connection, use a command object to fill a recordset from a stored procedure, then close the connection and pass back a disconnected recordset. My attempts so far fail as every time I close the connection, my recordset also closes (which means it is not disconnected).

Is there a property I must set somewhere to indicate that the recordset should be disconnected? I cannot set Recordset.ActiveConnection = False because I get an exception ("Cannot change the ActiveConnection property of a Recordset object which has a Command object as its source."). I do set the Command.ActiveConnection = False, but that doesn't stop the recordset from closing as soon as I close the connection object.

Snippet:

Dim conn as New ADODB.Connection()
conn.Open("connectionString", "UserID", "Password")
Dim cmd as New ADODB.Command()
' Set some parameters on the command.
cmd.ActiveConnection = conn
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc
Dim rs as New ADODB.Recordset()
rs.Open(cmd)
Dim clonedRS as ADODB.Recordset = rs.Clone()  ' one attempt to disconnect recordset
rs.Close()  ' Does not close cloned recordset
cmd.ActiveConnection = Nothing   ' another try at disconnecting recordset
conn.Close()  ' Always closes the recordset, even the cloned one
return clonedRS  ' Sadly, this is closed now.

Answer

Tim picture Tim · Sep 3, 2011

I don't know if this will solve your problem, but I did a Google search and came upon this article Disconnect an ADO Recordset generated from a Command object, which you might be able to use to modify your code as follows:

Dim conn as New ADODB.Connection()
conn.Open("connectionString", "UserID", "Password")
Dim cmd as New ADODB.Command()
' Set some parameters on the command.
cmd.ActiveConnection = conn
cmd.CommandText = "StoredProcedureName"
cmd.CommandType = ADODB.CommandTypeEnum.adCmdStoredProc

Dim rs As ADODB.Recordset

With rs
    .CursorLocation = adUseClient
    .Open cmd, CursorType:=adOpenStatic, Options:=adCmdStoredProc
    Set .ActiveConnection = Nothing
End With

Dim clonedRS As ADODB.Recordset = rs

Set cmd = Nothing

conn.Close()
rs.Close()
Set conn = Nothing
Set rs = Nothing

Return clonedRS

There's another example from 4GuysFromRolla Using Disconnected Recordsets that has the same approach.

EDIT

Fleshed out the example.