C#中的SqlConnection类是用来做什么的?如何使用它?

来源:这里教程网 时间:2026-02-21 17:27:11 作者:

SqlConnection 类是 C# 中用于连接 SQL Server 数据库的核心类,属于 System.Data.SqlClient 命名空间(在 .NET Core 及更高版本中推荐使用 Microsoft.Data.SqlClient)。它的主要作用是建立与 SQL Server 数据库的连接,为后续执行命令、查询数据等操作提供通道。

基本用途

SqlConnection 负责管理应用程序和 SQL Server 之间的物理连接。它不执行查询,但为 SqlCommand、SqlDataAdapter 等其他数据库操作类提供连接支持。

如何使用 SqlConnection

使用 SqlConnection 的典型步骤包括:配置连接字符串、创建连接对象、打开连接、执行操作、关闭连接。推荐使用 using 语句确保连接被正确释放。

以下是具体使用方式:

1. 添加命名空间引用

using System.Data.SqlClient;

(注意:若使用 .NET Core/.NET 5+,建议安装 Microsoft.Data.SqlClient NuGet 包并引用 using Microsoft.Data.SqlClient;

2. 定义连接字符串

连接字符串包含服务器地址、数据库名、认证方式等信息。

例如:

string connectionString = "Server=localhost;Database=MyDB;User Id=myuser;Password=mypassword;";
// 或使用 Windows 身份验证
string connectionString = "Server=localhost;Database=MyDB;Integrated Security=true;";

3. 创建并打开连接

使用 using 语句可自动管理连接的打开与关闭,避免资源泄漏。

示例代码:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    try
    {
        connection.Open();
        Console.WriteLine("数据库连接成功!");
<pre class="brush:php;toolbar:false;">    // 在这里执行 SqlCommand 查询或操作
}
catch (SqlException ex)
{
    Console.WriteLine("数据库错误: " + ex.Message);
}
// using 结束时,连接自动关闭并释放资源

}

4. 与 SqlCommand 配合执行操作

连接建立后,通常配合 SqlCommand 执行 SQL 语句。

例如查询数据:

using (SqlConnection connection = new SqlConnection(connectionString))
{
    string sql = "SELECT Name FROM Users WHERE Age > @age";
    using (SqlCommand command = new SqlCommand(sql, connection))
    {
        command.Parameters.AddWithValue("@age", 18);
<pre class="brush:php;toolbar:false;">    connection.Open();
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            Console.WriteLine(reader["Name"].ToString());
        }
    }
}

}

关键注意事项

始终使用 using 语句:确保连接即使出错也能被正确关闭。 不要手动调用 Close() 或 Dispose():using 语句会自动处理。 连接字符串安全:避免硬编码密码,建议使用配置文件或环境变量,并启用加密(如连接字符串中的 Encrypt=true)。 异常处理:捕获 SqlException 以处理连接失败、超时、登录错误等问题。

基本上就这些。SqlConnection 是访问 SQL Server 的第一步,掌握它才能进行后续的数据操作。

相关推荐