SqlConnection 類別


表示對 SQL Server 資料庫的連線。Represents a connection to a SQL Server database. 無法繼承這個類別。This class cannot be inherited.

public ref class SqlConnection sealed : System::Data::Common::DbConnection, ICloneable, IDisposable
public sealed class SqlConnection : System.Data.Common.DbConnection, ICloneable, IDisposable
type SqlConnection = class
    inherit DbConnection
    interface IDbConnection
    interface ICloneable
    interface IDisposable
Public NotInheritable Class SqlConnection
Inherits DbConnection
Implements ICloneable, IDisposable


下列範例會建立 SqlCommandSqlConnectionThe following example creates a SqlCommand and a SqlConnection. 隨即開啟 SqlConnection,並將其設定為 SqlCommandConnectionThe SqlConnection is opened and set as the Connection for the SqlCommand. 然後,此範例會呼叫 ExecuteNonQueryThe example then calls ExecuteNonQuery. 為了達成此目的,會將連接字串和查詢字串(Transact-SQLTransact-SQL INSERT 語句)傳遞給 ExecuteNonQueryTo accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is a Transact-SQLTransact-SQL INSERT statement. 當程式碼結束 using 區塊時,就會自動關閉連接。The connection is closed automatically when the code exits the using block.

private static void CreateCommand(string queryString,
    string connectionString)
    using (SqlConnection connection = new SqlConnection(
        SqlCommand command = new SqlCommand(queryString, connection);
Public Sub CreateCommand(ByVal queryString As String, _
  ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)
    End Using
End Sub


SqlConnection 物件表示 SQL Server 資料來源的唯一會話。A SqlConnection object represents a unique session to a SQL Server data source. 在用戶端/伺服器資料庫系統中,它相當於與伺服器的網路連接。With a client/server database system, it is equivalent to a network connection to the server. SqlConnection 會與 SqlDataAdapterSqlCommand 一起使用,以在連接到 Microsoft SQL Server 資料庫時提高效能。SqlConnection is used together with SqlDataAdapter and SqlCommand to increase performance when connecting to a Microsoft SQL Server database. 針對所有協力廠商 SQL Server 產品和其他 OLE DB 支援的資料來源,請使用 OleDbConnectionFor all third-party SQL Server products and other OLE DB-supported data sources, use OleDbConnection.

當您建立 SqlConnection的實例時,所有屬性都會設為其初始值。When you create an instance of SqlConnection, all properties are set to their initial values. 如需這些值的清單,請參閱 SqlConnection 的函式。For a list of these values, see the SqlConnection constructor.

如需連接字串中的關鍵字清單,請參閱 ConnectionStringSee ConnectionString for a list of the keywords in a connection string.

如果 SqlConnection 超出範圍,則不會將它關閉。If the SqlConnection goes out of scope, it won't be closed. 因此,您必須藉由呼叫 CloseDispose明確地關閉連接。Therefore, you must explicitly close the connection by calling Close or Dispose. CloseDispose 的功能相同。Close and Dispose are functionally equivalent. 如果連接共用值 Pooling 設定為 trueyes,基礎連接就會傳回至連接集區。If the connection pooling value Pooling is set to true or yes, the underlying connection is returned back to the connection pool. 另一方面,如果 Pooling 設定為 falseno,則會實際關閉與伺服器的基礎連接。On the other hand, if Pooling is set to false or no, the underlying connection to the server is actually closed.


從連接集區中擷取連接或將連接傳回連接集區時,系統不會在伺服器上引發登入和登出事件,因為當連接傳回連接集區時,連接實際上並未關閉。Login and logout events will not be raised on the server when a connection is fetched from or returned to the connection pool, because the connection is not actually closed when it is returned to the connection pool. 如需詳細資訊,請參閱 SQL Server 連共用ADO.NET)For more information, see SQL Server Connection Pooling (ADO.NET).

若要確保一律關閉連接,請開啟 using 區塊內的連接,如下列程式碼片段所示。To ensure that connections are always closed, open the connection inside of a using block, as shown in the following code fragment. 這麼做可確保當程式碼結束區塊時,會自動關閉連接。Doing so ensures that the connection is automatically closed when the code exits the block.

Using connection As New SqlConnection(connectionString)  
    ' Do work here; connection closed on following line.  
End Using  
using (SqlConnection connection = new SqlConnection(connectionString))  
        // Do work here; connection closed on following line.  


若要部署高效能應用程式,您必須使用連接共用。To deploy high-performance applications, you must use connection pooling. 當您使用 SQL Server 的 .NET Framework Data Provider 時,您不需要啟用連接共用,因為提供者會自動管理此設定,但您可以修改某些設定。When you use the .NET Framework Data Provider for SQL Server, you do not have to enable connection pooling because the provider manages this automatically, although you can modify some settings. 如需詳細資訊,請參閱 SQL Server 連共用ADO.NET)For more information, see SQL Server Connection Pooling (ADO.NET).

如果 SqlException 是由執行 SqlCommand的方法所產生,則當嚴重性層級為19或更小時,SqlConnection 會保持開啟。If a SqlException is generated by the method executing a SqlCommand, the SqlConnection remains open when the severity level is 19 or less. 當嚴重性層級為20或更大時,伺服器通常會關閉 SqlConnectionWhen the severity level is 20 or greater, the server ordinarily closes the SqlConnection. 但是,使用者可以再次開啟連線,然後繼續進行。However, the user can reopen the connection and continue.

建立 SqlConnection 物件實例的應用程式,可以透過設定宣告式或命令式安全性要求,要求所有直接和間接呼叫端都具有足夠的程式碼許可權。An application that creates an instance of the SqlConnection object can require all direct and indirect callers to have sufficient permission to the code by setting declarative or imperative security demands. SqlConnection 使用 SqlClientPermission 物件來進行安全性要求。SqlConnection makes security demands using the SqlClientPermission object. 使用者可以使用 SqlClientPermissionAttribute 物件來驗證其程式碼是否有足夠的許可權。Users can verify that their code has sufficient permissions by using the SqlClientPermissionAttribute object. 使用者和系統管理員也可以使用caspol.exe (代碼啟用安全性原則工具)來修改電腦、使用者和企業層級的安全性原則。Users and administrators can also use the Caspol.exe (Code Access Security Policy Tool) to modify security policy at the machine, user, and enterprise levels. 如需詳細資訊,請參閱 .NET 的安全性For more information, see Security in .NET. 如需示範如何使用安全性需求的範例,請參閱代碼啟用安全性和 ADO.NETFor an example demonstrating how to use security demands, see Code Access Security and ADO.NET.

如需從伺服器處理警告和參考用訊息的詳細資訊,請參閱連接事件For more information about handling warning and informational messages from the server, see Connection Events. 如需 SQL Server 引擎錯誤和錯誤訊息的詳細資訊,請參閱資料庫引擎事件和錯誤For more information about SQL Server engine errors and error messages, see Database Engine Events and Errors.


您可以強制 TCP,而不是共用記憶體。You can force TCP instead of shared memory. 若要這麼做,您可以在連接字串中的伺服器名稱前面加上 tcp:,或者可以使用 localhost。You can do that by prefixing tcp: to the server name in the connection string or you can use localhost.



初始化 SqlConnection 類別的新執行個體。Initializes a new instance of the SqlConnection class.


指定包含連接字串的字串時,初始化 SqlConnection 類別的新執行個體。Initializes a new instance of the SqlConnection class when given a string that contains the connection string.

SqlConnection(String, SqlCredential)

指定不使用 SqlConnection 和包含使用者 ID 和密碼之 Integrated Security = true 物件的連接字串,初始化 SqlCredential 類別的新執行個體。Initializes a new instance of the SqlConnection class given a connection string, that does not use Integrated Security = true and a SqlCredential object that contains the user ID and password.



取得或設定此連接的存取權杖。Gets or sets the access token for the connection.


取得值,指出元件是否能引發事件。Gets a value indicating whether the component can raise an event.

(繼承來源 Component)

最近連線的連線 ID,無論連線是否成功。The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed.


針對 Always Encrypted 功能,取得或設定資料行加密金鑰快取中資料行加密金鑰項目的存留時間。Gets or sets the time-to-live for column encryption key entries in the column encryption key cache for the Always Encrypted feature. 預設值是 2 小時。The default value is 2 hours. 0 表示完全沒有快取。0 means no caching at all.


取得或設定值,指出是否要針對根據已啟用 Always Encrypted 的資料庫執行的參數化查詢,啟用 (true) 或停用 (false) 查詢中繼資料快取。Gets or sets a value that indicates whether query metadata caching is enabled (true) or not (false) for parameterized queries running against Always Encrypted enabled databases. 預設值是 true。The default value is true.


可讓您為資料庫伺服器設定受信任機碼路徑的清單。Allows you to set a list of trusted key paths for a database server. 如果在處理應用程式查詢時,驅動程式收到的機碼路徑不在清單上,查詢就會失敗。If while processing an application query the driver receives a key path that is not on the list, the query will fail. 這個屬性會提供額外的保護以對抗安全性攻擊,事關受危害的 SQL Server 提供虛構的機碼路徑,這有可能導致金鑰存放區認證洩漏。This property provides additional protection against security attacks that involve a compromised SQL Server providing fake key paths, which may lead to leaking key store credentials.


取得或設定用來開啟 SQL Server 資料庫的字串。Gets or sets the string used to open a SQL Server database.


取得在終止嘗試並產生錯誤前嘗試建立連接的等待時間 (以秒為單位)。Gets the time to wait (in seconds) while trying to establish a connection before terminating the attempt and generating an error.


取得包含 IContainerComponentGets the IContainer that contains the Component.

(繼承來源 Component)

取得或設定這個連接的 SqlCredential 物件。Gets or sets the SqlCredential object for this connection.


取得目前資料庫或要在連接開啟之後使用的資料庫名稱。Gets the name of the current database or the database to be used after a connection is opened.


取得要連線的 SQL Server 執行個體名稱。Gets the name of the instance of SQL Server to which to connect.


取得這個 DbProviderFactoryDbConnectionGets the DbProviderFactory for this DbConnection.

(繼承來源 DbConnection)

取得值,指出 Component 目前是否處於設計模式。Gets a value that indicates whether the Component is currently in design mode.

(繼承來源 Component)

取得附加在這個 Component 上的事件處理常式清單。Gets the list of event handlers that are attached to this Component.

(繼承來源 Component)

取得或設定 FireInfoMessageEventOnUserErrors 屬性。Gets or sets the FireInfoMessageEventOnUserErrors property.


取得用來與 SQL Server 執行個體通訊的網路封包大小 (位元組)。Gets the size (in bytes) of network packets used to communicate with an instance of SQL Server.


取得字串,其中包含用戶端連線的 SQL Server 執行個體版本。Gets a string that contains the version of the instance of SQL Server to which the client is connected.


取得或設定 ComponentISiteGets or sets the ISite of the Component.

(繼承來源 Component)

指出在連接上執行最近一次網路作業期間的 SqlConnection 狀態。Indicates the state of the SqlConnection during the most recent network operation performed on the connection.


設定為 true 時,啟用目前連接的統計資料蒐集。When set to true, enables statistics gathering for the current connection.


取得識別資料庫用戶端的字串。Gets a string that identifies the database client.



當在衍生類別中被覆寫時,會開始進行資料庫交易。When overridden in a derived class, starts a database transaction.

(繼承來源 DbConnection)
BeginDbTransactionAsync(IsolationLevel, CancellationToken)

以非同步方式開始資料庫交易。Asynchronously starts a database transaction.

(繼承來源 DbConnection)

啟動資料庫交易。Starts a database transaction.


使用指定的隔離等級啟動資料庫交易。Starts a database transaction with the specified isolation level.

BeginTransaction(IsolationLevel, String)

使用指定的隔離等級和交易名稱開始資料庫交易。Starts a database transaction with the specified isolation level and transaction name.


使用指定的異動名稱開始資料庫異動。Starts a database transaction with the specified transaction name.


以非同步方式開始資料庫交易。Asynchronously begins a database transaction.

(繼承來源 DbConnection)
BeginTransactionAsync(IsolationLevel, CancellationToken)

以非同步方式開始資料庫交易。Asynchronously begins a database transaction.

(繼承來源 DbConnection)

為開啟的 SqlConnection 變更目前的資料庫。Changes the current database for an open SqlConnection.

ChangeDatabaseAsync(String, CancellationToken)

以非同步方式針對開啟的連線變更目前的資料庫。Asynchronously changes the current database for an open connection.

(繼承來源 DbConnection)
ChangePassword(String, SqlCredential, SecureString)

變更 SqlCredential 物件中指定的使用者 SQL Server 密碼。Changes the SQL Server password for the user indicated in the SqlCredential object.

ChangePassword(String, String)

將連接字串中指示的使用者 SQL Server 密碼變更成提供的新密碼。Changes the SQL Server password for the user indicated in the connection string to the supplied new password.


清空連接集區。Empties the connection pool.


清空與特定連接關聯的連接集區。Empties the connection pool associated with the specified connection.


關閉與資料庫的連接。Closes the connection to the database. 這是關閉任何開啟連接的慣用方法。This is the preferred method of closing any open connection.


以非同步方式關閉與資料庫的連線。Asynchronously closes the connection to the database.

(繼承來源 DbConnection)

建立並傳回與 SqlCommand 關聯的 SqlConnection 物件。Creates and returns a SqlCommand object associated with the SqlConnection.


當在衍生類別中被覆寫時,建立並傳回與目前連線相關聯的 DbCommand 物件。When overridden in a derived class, creates and returns a DbCommand object associated with the current connection.

(繼承來源 DbConnection)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(繼承來源 MarshalByRefObject)

釋放 Component 所使用的所有資源。Releases all resources used by the Component.

(繼承來源 Component)

釋放 Component 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(繼承來源 Component)

以非同步方式處置連線物件。Asynchronously diposes the connection object.

(繼承來源 DbConnection)

將指定的異動登記為分散式異動。Enlists in the specified transaction as a distributed transaction.


將指定的異動登記為分散式異動。Enlists in the specified transaction as a distributed transaction.


判斷指定的物件是否等於目前的物件。Determines whether the specified object is equal to the current object.

(繼承來源 Object)

做為預設雜湊函式。Serves as the default hash function.

(繼承來源 Object)

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)

傳回這個 SqlConnection 之資料來源的結構描述資訊。Returns schema information for the data source of this SqlConnection. 如需結構描述的詳細資訊,請參閱 SQL Server 結構描述集合For more information about scheme, see SQL Server Schema Collections.


使用結構描述名稱的特定字串,傳回這個 SqlConnection 之資料來源的結構描述資訊。Returns schema information for the data source of this SqlConnection using the specified string for the schema name.

GetSchema(String, String[])

使用結構描述名稱的特定字串和限制值的特定字串陣列,傳回這個 SqlConnection 的資料來源的結構描述資訊。Returns schema information for the data source of this SqlConnection using the specified string for the schema name and the specified string array for the restriction values.


傳回表示 Component 或其 Container 所提供之服務的物件。Returns an object that represents a service provided by the Component or by its Container.

(繼承來源 Component)

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)

取得存留期服務物件,以控制這個執行個體的存留期原則。Obtains a lifetime service object to control the lifetime policy for this instance.

(繼承來源 MarshalByRefObject)

建立目前 Object 的淺層複製。Creates a shallow copy of the current Object.

(繼承來源 Object)

建立目前 MarshalByRefObject 物件的淺層複本。Creates a shallow copy of the current MarshalByRefObject object.

(繼承來源 MarshalByRefObject)

引發 StateChange 事件。Raises the StateChange event.

(繼承來源 DbConnection)

使用 ConnectionString 所指定的屬性設定,開啟資料庫連接。Opens a database connection with the property settings specified by the ConnectionString.


非同步版本的 Open(),這個版本會透過 ConnectionString 所指定的設定開啟資料庫連接。An asynchronous version of Open(), which opens a database connection with the settings specified by the ConnectionString. 這個方法會叫用虛擬方法 OpenAsync(CancellationToken) 與 CancellationToken.None。This method invokes the virtual method OpenAsync(CancellationToken) with CancellationToken.None.

(繼承來源 DbConnection)

非同步版本的 Open(),這個版本會透過 ConnectionString 所指定的屬性設定開啟資料庫連接。An asynchronous version of Open(), which opens a database connection with the property settings specified by the ConnectionString. 取消語彙基元可用於要求在連線逾時之前捨棄作業。The cancellation token can be used to request that the operation be abandoned before the connection timeout elapses. 例外狀況將經由傳回的工作傳播。Exceptions will be propagated via the returned Task. 如果超過連接逾時期限而未順利連線,傳回的工作會標示為失敗並發生例外狀況。If the connection timeout time elapses without successfully connecting, the returned Task will be marked as faulted with an Exception. 實作會傳回一項工作,而不需針對集區和非集區的連接封鎖呼叫的執行緒。The implementation returns a Task without blocking the calling thread for both pooled and non-pooled connections.


註冊資料行加密金鑰存放區提供者。Registers the column encryption key store providers.


如果啟用統計資料蒐集,則所有值都會重設為零。If statistics gathering is enabled, all values are reset to zero.


呼叫方法時,傳回統計資料的名稱值配對集合。Returns a name value pair collection of statistics at the point in time the method is called.


傳回任何包含 Component 名稱的 StringReturns a String containing the name of the Component, if any. 不應覆寫此方法。This method should not be overridden.

(繼承來源 Component)



當此元件由 Dispose() 方法的呼叫處置時發生。Occurs when the component is disposed by a call to the Dispose() method.

(繼承來源 Component)

發生於 SQL Server 傳回警告或告知性訊息時。Occurs when SQL Server returns a warning or informational message.


當連線的狀態變更時發生。Occurs when the state of the connection changes.



建立目前執行個體複本的新物件。Creates a new object that is a copy of the current instance.


開始資料庫交易。Begins a database transaction.


使用指定的 IsolationLevel 值來開始資料庫交易。Begins a database transaction with the specified IsolationLevel value.


建立並傳回與連接相關聯的 Command 物件。Creates and returns a Command object that is associated with the connection.