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。

适用于

另请参阅