Bagikan melalui


SqlCommand.Connection Properti

Definisi

Mendapatkan atau mengatur yang SqlConnection digunakan oleh instans ini dari 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

Nilai Properti

Koneksi ke sumber data. Nilai defaultnya adalahnull .

Pengecualian

Properti Connection diubah saat perintah terdaftar dalam transaksi.

Contoh

Contoh berikut membuat SqlCommand dan mengatur beberapa propertinya.

// <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>
    }
}

Keterangan

Jika perintah terdaftar dalam transaksi yang ada, dan koneksi diubah, mencoba menjalankan perintah akan melemparkan InvalidOperationException.

Transaction Jika properti tidak null dan transaksi telah diterapkan atau digulung balik, Transaction diatur ke null.

Berlaku untuk