SqlCommand.Connection 属性

获取或设置 SqlCommand 的此实例使用的 SqlConnection

**命名空间:**System.Data.SqlClient
**程序集:**System.Data(在 system.data.dll 中)

语法

声明
Public Property Connection As SqlConnection
用法
Dim instance As SqlCommand
Dim value As SqlConnection

value = instance.Connection

instance.Connection = value
public SqlConnection Connection { get; set; }
public:
property SqlConnection^ Connection {
    SqlConnection^ get ();
    void set (SqlConnection^ value);
}
/** @property */
public SqlConnection get_Connection ()

/** @property */
public void set_Connection (SqlConnection value)
public function get Connection () : SqlConnection

public function set Connection (value : SqlConnection)

属性值

与数据源的连接。默认值为 空引用(在 Visual Basic 中为 Nothing)。

异常

异常类型 条件

InvalidOperationException

在事务进行过程中更改了 Connection 属性。

备注

如果在事务进行过程中设置 Connection,而且 Transaction 属性不为空,则会生成 InvalidOperationException。如果 Transaction 属性不为空,而事务已经提交或回滚,则 Transaction 设置为 null。

示例

下面的示例创建一个 SqlCommand 并设置它的一些属性。

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
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]));
        }
    }
}

平台

Windows 98、Windows 2000 SP4、Windows CE、Windows Millennium Edition、Windows Mobile for Pocket PC、Windows Mobile for Smartphone、Windows Server 2003、Windows XP Media Center Edition、Windows XP Professional x64 Edition、Windows XP SP2、Windows XP Starter Edition

.NET Framework 并不是对每个平台的所有版本都提供支持。有关受支持版本的列表,请参见系统要求

版本信息

.NET Framework

受以下版本支持:2.0、1.1、1.0

.NET Compact Framework

受以下版本支持:2.0、1.0

请参见

参考

SqlCommand 类
SqlCommand 成员
System.Data.SqlClient 命名空间
SqlCommand.CommandText 属性
SqlCommand.CommandTimeout 属性
SqlCommand.CommandType 属性