SqlCommand.Connection 属性

SqlCommand.Connection 属性

获取或设置 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

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值