Share via


SqlCommand.Connection 屬性

定義

取得或設定 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。

適用於