共用方式為


SqlCommand.Connection 屬性

定義

取得或設定 SqlCommand 的這個執行個體所使用的 SqlConnection

public:
 property System::Data::SqlClient::SqlConnection ^ Connection { System::Data::SqlClient::SqlConnection ^ get(); void set(System::Data::SqlClient::SqlConnection ^ value); };
public System.Data.SqlClient.SqlConnection Connection { get; set; }
[System.Data.DataSysDescription("DbCommand_Connection")]
public System.Data.SqlClient.SqlConnection Connection { get; set; }
member this.Connection : System.Data.SqlClient.SqlConnection with get, set
[<System.Data.DataSysDescription("DbCommand_Connection")>]
member this.Connection : System.Data.SqlClient.SqlConnection with get, set
Public Property Connection As SqlConnection

屬性值

資料來源的連接。 預設值是 null

屬性

例外狀況

Connection 屬性已在命令於交易中登錄時變更。

範例

下列範例會建立 , SqlCommand 並設定其部分屬性。

private static void CreateCommand(string queryString,
    string connectionString)
{
    using (SqlConnection connection = new SqlConnection(
               connectionString))
    {
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandTimeout = 15;
        command.CommandType = CommandType.Text;
        command.CommandText = queryString;

        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
        }
    }
}
Public Sub CreateCommand(ByVal queryString As String, _
  ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand()
        command.Connection = connection
        command.CommandTimeout = 15
        command.CommandType = CommandType.Text
        command.CommandText = queryString

        connection.Open()
        Dim reader As SqlDataReader = command.ExecuteReader()
            While reader.Read()
            Console.WriteLine(String.Format("{0}, {1}", _
                reader(0), reader(1)))
        End While
    End Using
End Sub

備註

如果在現有交易中登記命令,且連線已變更,則嘗試執行命令將會擲回 InvalidOperationException

如果 Transaction 屬性不是 null,且異動已經認可或回復,則 Transaction 會設定為 null。

適用於

另請參閱