SqlCommand.Connection 属性
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
获取或设置 SqlConnection 的此实例 SqlCommand 使用的 。
public:
property Microsoft::Data::SqlClient::SqlConnection ^ Connection { Microsoft::Data::SqlClient::SqlConnection ^ get(); void set(Microsoft::Data::SqlClient::SqlConnection ^ value); };
public Microsoft.Data.SqlClient.SqlConnection Connection { get; set; }
member this.Connection : Microsoft.Data.SqlClient.SqlConnection with get, set
Public Property Connection As SqlConnection
属性值
到数据源的连接。 默认值为null
.
例外
命令在事务中登记时 Connection 属性被更改。
示例
以下示例创建 SqlCommand 并设置其一些属性。
// <Snippet1>
using System;
using System.Data;
using Microsoft.Data.SqlClient;
namespace SqlCommandCS
{
class Program
{
static void Main()
{
string str = "Data Source=(local);Initial Catalog=Northwind;"
+ "Integrated Security=SSPI";
string qs = "SELECT OrderID, CustomerID FROM dbo.Orders;";
CreateCommand(qs, str);
}
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]));
}
}
}
// </Snippet1>
}
}
注解
如果命令已在现有事务中登记,并且连接已更改,则尝试执行该命令将引发 InvalidOperationException。
如果 Transaction 属性不为 null,而事务已提交或回滚,则会将 Transaction 设置为 null。