SqlConnection SqlConnection SqlConnection SqlConnection Class

定义

表示到 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
继承
实现

示例

下面的示例创建SqlCommand和一个SqlConnectionThe following example creates a SqlCommand and a SqlConnection. SqlConnection打开,并设置为ConnectionSqlCommandThe SqlConnection is opened and set as the Connection for the SqlCommand. 该示例然后调用ExecuteNonQueryThe example then calls ExecuteNonQuery. 若要完成此操作,请ExecuteNonQuery连接字符串和一个查询字符串传递Transact-SQLTransact-SQLINSERT 语句。To accomplish this, the ExecuteNonQuery is passed a connection string and a query string that is a Transact-SQLTransact-SQL INSERT statement. 使用在代码退出时会自动关闭连接块。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(
               connectionString))
    {
        SqlCommand command = new SqlCommand(queryString, connection);
        command.Connection.Open();
        command.ExecuteNonQuery();
    }
}
Public Sub CreateCommand(ByVal queryString As String, _
  ByVal connectionString As String)
    Using connection As New SqlConnection(connectionString)
        Dim command As New SqlCommand(queryString, connection)
        command.Connection.Open()
        command.ExecuteNonQuery()
    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.

请参阅ConnectionString有关连接字符串中的关键字的列表。See ConnectionString for a list of the keywords in a connection string.

如果SqlConnection超出范围,则不会关闭。If the SqlConnection goes out of scope, it won't be closed. 因此,必须显式关闭连接通过调用CloseDisposeTherefore, 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)  
    connection.Open()  
    ' Do work here; connection closed on following line.  
End Using  
using (SqlConnection connection = new SqlConnection(connectionString))  
    {  
        connection.Open();  
        // Do work here; connection closed on following line.  
    }  

备注

若要部署高性能应用程序,必须使用连接池。To deploy high-performance applications, you must use connection pooling. SQL Server 中使用.NET Framework 数据提供程序时,您无需启用连接池,因为提供程序管理是自动,尽管可以修改某些设置。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,则SqlConnection保持打开状态时的严重级别为 19 或更少。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 实现: 在连接中的服务器名称为字符串,也可以使用本地主机。You can do that by prefixing tcp: to the server name in the connection string or you can use localhost.

构造函数

SqlConnection() SqlConnection() SqlConnection() SqlConnection()

初始化 SqlConnection 类的新实例。Initializes a new instance of the SqlConnection class.

SqlConnection(String) SqlConnection(String) SqlConnection(String) SqlConnection(String)

如果给定包含连接字符串的字符串,则初始化 SqlConnection 类的新实例。Initializes a new instance of the SqlConnection class when given a string that contains the connection string.

SqlConnection(String, SqlCredential) SqlConnection(String, SqlCredential) SqlConnection(String, SqlCredential) SqlConnection(String, SqlCredential)

在给定连接字符串的情况下,初始化 SqlConnection 类的新实例,该连接字符串不使用 Integrated Security = true 和包含用户 ID 和密码的 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.

属性

AccessToken AccessToken AccessToken AccessToken

获取或设置用于连接的访问令牌。Gets or sets the access token for the connection.

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

获取一个指示组件是否可以引发事件的值。Gets a value indicating whether the component can raise an event.

(Inherited from Component)
ClientConnectionId ClientConnectionId ClientConnectionId ClientConnectionId

最近连接尝试连接的 ID,无论该尝试是成功还是失败。The connection ID of the most recent connection attempt, regardless of whether the attempt succeeded or failed.

ColumnEncryptionKeyCacheTtl ColumnEncryptionKeyCacheTtl ColumnEncryptionKeyCacheTtl ColumnEncryptionKeyCacheTtl

在用于 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.

ColumnEncryptionQueryMetadataCacheEnabled ColumnEncryptionQueryMetadataCacheEnabled ColumnEncryptionQueryMetadataCacheEnabled ColumnEncryptionQueryMetadataCacheEnabled

获取或设置一个值,该值指示对参数化查询(针对已启用 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.

ColumnEncryptionTrustedMasterKeyPaths ColumnEncryptionTrustedMasterKeyPaths ColumnEncryptionTrustedMasterKeyPaths ColumnEncryptionTrustedMasterKeyPaths

允许你设置数据库服务器的受信任密钥路径列表。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.

ConnectionString ConnectionString ConnectionString ConnectionString

获取或设置用于打开 SQL Server 数据库的字符串。Gets or sets the string used to open a SQL Server database.

ConnectionTimeout ConnectionTimeout ConnectionTimeout ConnectionTimeout

获取终止尝试并生成错误之前在尝试建立连接时所等待的时间。Gets the time to wait while trying to establish a connection before terminating the attempt and generating an error.

Container Container Container Container

获取 IContainer,它包含 ComponentGets the IContainer that contains the Component.

(Inherited from Component)
Credential Credential Credential Credential

获取或设置此连接的 SqlCredential 对象。Gets or sets the SqlCredential object for this connection.

Credentials Credentials Credentials Credentials
Database Database Database Database

获取当前数据库的名称或打开连接后要使用的数据库的名称。Gets the name of the current database or the database to be used after a connection is opened.

DataSource DataSource DataSource DataSource

获取要连接的 SQL Server 的实例的名称。Gets the name of the instance of SQL Server to which to connect.

DesignMode DesignMode DesignMode DesignMode

获取一个值,用以指示 Component 当前是否处于设计模式。Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Events Events Events Events

获取附加到此 Component 的事件处理程序的列表。Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
FireInfoMessageEventOnUserErrors FireInfoMessageEventOnUserErrors FireInfoMessageEventOnUserErrors FireInfoMessageEventOnUserErrors

获取或设置 FireInfoMessageEventOnUserErrors 属性。Gets or sets the FireInfoMessageEventOnUserErrors property.

PacketSize PacketSize PacketSize PacketSize

获取用于与 SQL Server 的实例进行通信的网络数据包的大小(以字节为单位)。Gets the size (in bytes) of network packets used to communicate with an instance of SQL Server.

ServerVersion ServerVersion ServerVersion ServerVersion

获取一个字符串,其中包含客户端所连接到的 SQL Server 的实例的版本。Gets a string that contains the version of the instance of SQL Server to which the client is connected.

Site Site Site Site

获取或设置 ComponentISiteGets or sets the ISite of the Component.

(Inherited from Component)
State State State State

最近在连接上执行网络操作时表示 SqlConnection 的状态。Indicates the state of the SqlConnection during the most recent network operation performed on the connection.

StatisticsEnabled StatisticsEnabled StatisticsEnabled StatisticsEnabled

如果设置为 true,则对当前连接启用统计信息收集。When set to true, enables statistics gathering for the current connection.

WorkstationId WorkstationId WorkstationId WorkstationId

获取一个标识数据库客户端的字符串。Gets a string that identifies the database client.

方法

BeginTransaction() BeginTransaction() BeginTransaction() BeginTransaction()

开始数据库事务。Starts a database transaction.

BeginTransaction(IsolationLevel) BeginTransaction(IsolationLevel) BeginTransaction(IsolationLevel) BeginTransaction(IsolationLevel)

以指定的隔离级别启动数据库事务。Starts a database transaction with the specified isolation level.

BeginTransaction(IsolationLevel, String) BeginTransaction(IsolationLevel, String) BeginTransaction(IsolationLevel, String) BeginTransaction(IsolationLevel, String)

以指定的隔离级别和事务名称启动数据库事务。Starts a database transaction with the specified isolation level and transaction name.

BeginTransaction(String) BeginTransaction(String) BeginTransaction(String) BeginTransaction(String)

以指定的事务名称启动数据库事务。Starts a database transaction with the specified transaction name.

ChangeDatabase(String) ChangeDatabase(String) ChangeDatabase(String) ChangeDatabase(String)

更改已打开的 SqlConnection 的当前数据库。Changes the current database for an open SqlConnection.

ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString) ChangePassword(String, SqlCredential, SecureString)

更改 SqlCredential 对象中指示的用户的 SQL Server 密码。Changes the SQL Server password for the user indicated in the SqlCredential object.

ChangePassword(String, String) ChangePassword(String, String) ChangePassword(String, String) ChangePassword(String, String)

将连接字符串中指示的用户的 SQL Server 密码更改为提供的新密码。Changes the SQL Server password for the user indicated in the connection string to the supplied new password.

ClearAllPools() ClearAllPools() ClearAllPools() ClearAllPools()

清空连接池。Empties the connection pool.

ClearPool(SqlConnection) ClearPool(SqlConnection) ClearPool(SqlConnection) ClearPool(SqlConnection)

清空与指定连接关联的连接池。Empties the connection pool associated with the specified connection.

Close() Close() Close() Close()

关闭与数据库之间的连接。Closes the connection to the database. 此方法是关闭任何打开连接的首选方法。This is the preferred method of closing any open connection.

CreateCommand() CreateCommand() CreateCommand() CreateCommand()

创建并返回与 SqlConnection 关联的 SqlCommand 对象。Creates and returns a SqlCommand object associated with the SqlConnection.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

释放由 Component 使用的所有资源。Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

释放由 Component 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
EnlistDistributedTransaction(ITransaction) EnlistDistributedTransaction(ITransaction) EnlistDistributedTransaction(ITransaction) EnlistDistributedTransaction(ITransaction)

在指定的事务中登记为分布式事务。Enlists in the specified transaction as a distributed transaction.

EnlistTransaction(Transaction) EnlistTransaction(Transaction) EnlistTransaction(Transaction) EnlistTransaction(Transaction)

在指定的事务中登记为分布式事务。Enlists in the specified transaction as a distributed transaction.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetSchema() GetSchema() GetSchema() GetSchema()

返回此 SqlConnection 的数据源的架构信息。Returns schema information for the data source of this SqlConnection. 有关架构的详细信息,请参阅 SQL Server 架构集合For more information about scheme, see SQL Server Schema Collections.

GetSchema(String) GetSchema(String) GetSchema(String) GetSchema(String)

通过使用架构名称的指定字符串,返回此 SqlConnection 的数据源的架构信息。Returns schema information for the data source of this SqlConnection using the specified string for the schema name.

GetSchema(String, String[]) GetSchema(String, String[]) GetSchema(String, String[]) 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.

GetService(Type) GetService(Type) GetService(Type) GetService(Type)

返回一个对象,该对象表示由 Component 或它的 Container 提供的服务。Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Open() Open() Open() Open()

使用由 ConnectionString 指定的属性设置打开一个数据库连接。Opens a database connection with the property settings specified by the ConnectionString.

OpenAsync(CancellationToken) OpenAsync(CancellationToken) OpenAsync(CancellationToken) OpenAsync(CancellationToken)

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.

RegisterColumnEncryptionKeyStoreProviders(IDictionary<String,SqlColumnEncryptionKeyStoreProvider>) RegisterColumnEncryptionKeyStoreProviders(IDictionary<String,SqlColumnEncryptionKeyStoreProvider>) RegisterColumnEncryptionKeyStoreProviders(IDictionary<String,SqlColumnEncryptionKeyStoreProvider>) RegisterColumnEncryptionKeyStoreProviders(IDictionary<String,SqlColumnEncryptionKeyStoreProvider>)

注册列加密密钥存储提供程序。Registers the column encryption key store providers.

ResetStatistics() ResetStatistics() ResetStatistics() ResetStatistics()

如果启用了统计信息收集,所有值都将重置为零。If statistics gathering is enabled, all values are reset to zero.

RetrieveStatistics() RetrieveStatistics() RetrieveStatistics() RetrieveStatistics()

调用此方法时,将返回统计信息的名称值对集合。Returns a name value pair collection of statistics at the point in time the method is called.

ToString() ToString() ToString() ToString()

返回包含 Component 的名称的 String(如果有)。Returns a String containing the name of the Component, if any. 不应重写此方法。This method should not be overridden.

(Inherited from Component)

事件

Disposed Disposed Disposed Disposed

当通过调用 Dispose() 方法释放组件时发生。Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)
InfoMessage InfoMessage InfoMessage InfoMessage

当 SQL Server 返回一个警告或信息性消息时发生。Occurs when SQL Server returns a warning or informational message.

StateChange StateChange StateChange StateChange

当连接的状态更改时发生。Occurs when the state of the connection changes.

显式界面实现

ICloneable.Clone() ICloneable.Clone() ICloneable.Clone() ICloneable.Clone()

创建作为当前实例副本的新对象。Creates a new object that is a copy of the current instance.

IDbConnection.BeginTransaction() IDbConnection.BeginTransaction() IDbConnection.BeginTransaction() IDbConnection.BeginTransaction()

开始一项数据库事务。Begins a database transaction.

IDbConnection.BeginTransaction(IsolationLevel) IDbConnection.BeginTransaction(IsolationLevel) IDbConnection.BeginTransaction(IsolationLevel) IDbConnection.BeginTransaction(IsolationLevel)

以指定的 IsolationLevel 值开始数据库事务。Begins a database transaction with the specified IsolationLevel value.

IDbConnection.CreateCommand() IDbConnection.CreateCommand() IDbConnection.CreateCommand() IDbConnection.CreateCommand()

创建并返回一个与连接关联的命令对象。Creates and returns a Command object that is associated with the connection.

适用于

另请参阅