This documentation is archived and is not being maintained.

OleDbCommand.Connection Property

Gets or sets the OleDbConnection used by this instance of the OleDbCommand.

[Visual Basic]
Public Property Connection As OleDbConnection
[C#]
public OleDbConnection Connection {get; set;}
[C++]
public: __property OleDbConnection* get_Connection();
public: __property void set_Connection(OleDbConnection*);
[JScript]
public function get Connection() : OleDbConnection;
public function set Connection(OleDbConnection);

Property Value

The connection to a data source. The default value is a null reference (Nothing in Visual Basic).

Exceptions

Exception Type Condition
InvalidOperationException The Connection property was changed while a transaction was in progress.

Remarks

You cannot set the Connection, CommandType and CommandText properties if the current connection is performing an execute or fetch operation.

If you set Connection while a transaction is in progress and the Transaction property is not null, an InvalidOperationException is generated. If the Transaction property is not null and the transaction has already been committed or rolled back, Transaction is set to null.

Example

[Visual Basic, C#, C++] The following example creates an OleDbCommand and sets some of its properties.

[Visual Basic] 
Public Sub CreateMyOleDbCommand()
    Dim mySelectQuery As String = _
       "SELECT * FROM Categories ORDER BY CategoryID"
    Dim myCommand As New OleDbCommand(mySelectQuery)
    myCommand.Connection = New OleDbConnection _
       ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND_RW.MDB")
    myCommand.CommandTimeout = 20
End Sub

[C#] 
public void CreateMyOleDbCommand() 
{
   string mySelectQuery = "SELECT * FROM Categories ORDER BY CategoryID";
   OleDbCommand myCommand = new OleDbCommand(mySelectQuery);
   myCommand.Connection = new OleDbConnection
      ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND_RW.MDB");
   myCommand.CommandTimeout = 20;
}

[C++] 
public:
 void CreateMyOleDbCommand() 
 {
    String* mySelectQuery = S"SELECT * FROM Categories ORDER BY CategoryID";
    OleDbCommand* myCommand = new OleDbCommand(mySelectQuery);
    myCommand->Connection = new OleDbConnection
       (S"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=NWIND_RW.MDB");
    myCommand->CommandTimeout = 20;
 }

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family

See Also

OleDbCommand Class | OleDbCommand Members | System.Data.OleDb Namespace | CommandText | CommandTimeout | CommandType

Show: