獲取或設置 SqlCommand 的此實例使用的 SqlConnection。
[Visual Basic] Public Property Connection As SqlConnection [C#] public SqlConnection Connection {get; set;} [C++] public: __property SqlConnection* get_Connection(); public: __property void set_Connection(SqlConnection*); [JScript] public function get Connection() : SqlConnection; public function set Connection(SqlConnection);
屬性值
與數據源的連接。默認值爲空引用(Visual Basic 中爲 Nothing)。
異常
異常類型 | 條件 |
---|---|
InvalidOperationException | 在事務進行過程中更改了 Connection 屬性。 |
備註
如果在事務進行過程中設置 Connection,而且 Transaction 屬性不爲空,則會生成 InvalidOperationException。如果 Transaction 屬性不爲空,而事務已經提交或回滾,則 Transaction 設置爲空。
示例
[Visual Basic, C#, C++] 下面的示例將創建一個 SqlCommand 並設置它的一些屬性。
[Visual Basic] Public Sub CreateMySqlCommand() Dim mySelectQuery As String = "SELECT * FROM Categories ORDER BY CategoryID" Dim myConnectString As String = "Persist Security Info=False;Integrated Security=SSPI;database=northwind;server=mySQLServer" Dim myCommand As New SqlCommand(mySelectQuery) myCommand.Connection = New SqlConnection(myConnectString) myCommand.CommandTimeout = 15 myCommand.CommandType = CommandType.Text End Sub 'CreateMySqlCommand [C#] public void CreateMySqlCommand() { string mySelectQuery = "SELECT * FROM Categories ORDER BY CategoryID"; string myConnectString = "Persist Security Info=False;Integrated Security=SSPI;database=northwind;server=mySQLServer"; SqlCommand myCommand = new SqlCommand(mySelectQuery); myCommand.Connection = new SqlConnection(myConnectString); myCommand.CommandTimeout = 15; myCommand.CommandType = CommandType.Text; } [C++] public: void CreateMySqlCommand() { String* mySelectQuery = S"SELECT * FROM Categories ORDER BY CategoryID"; String* myConnectString = S"Persist Security Info=False;Integrated Security=SSPI;database=northwind;server=mySQLServer"; SqlCommand* myCommand = new SqlCommand(mySelectQuery); myCommand->Connection = new SqlConnection(myConnectString); myCommand->CommandTimeout = 15; myCommand->CommandType = CommandType::Text; }
[JScript] 沒有可用於 JScript 的示例。若要查看 Visual Basic、C# 或 C++ 示例,請單擊頁左上角的“語言篩選器”按鈕 。
要求
平臺: Windows 98, Windows NT 4.0, Windows ME, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 系列, .NET Framework 精簡版
請參見
SqlCommand 類 | SqlCommand 成員 | System.Data.SqlClient 命名空間 | CommandText | CommandTimeout | CommandType