.NET怎么连接并查询SQL Server数据库

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

.NET 连接并查询 SQL Server 数据库非常常见,主要通过 ADO.NET 实现,使用

SqlConnection
SqlCommand
等类来完成操作。以下是具体步骤和示例代码。

1. 安装必要的 NuGet 包(.NET Core/.NET 5+)

如果你使用的是 .NET Core 或更高版本,需要确保项目中包含用于连接 SQL Server 的数据库驱动: System.Data.SqlClient:适用于较老的项目 Microsoft.Data.SqlClient:推荐使用,微软官方维护的新版驱动,支持更多功能

在项目目录下运行命令:

dotnet add package Microsoft.Data.SqlClient

2. 编写连接字符串

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

Server=localhost;Database=YourDB;Trusted_Connection=true;Encrypt=False;

或使用 SQL Server 账号密码登录:

Server=localhost;Database=YourDB;User Id=your_user;Password=your_password;

建议将连接字符串放在

appsettings.json
中管理。

3. 使用 SqlConnection 和 SqlCommand 查询数据

以下是一个简单的同步查询示例,从表中读取数据:

using System;
using Microsoft.Data.SqlClient;
class Program
{
    static void Main()
    {
        string connectionString = "Server=localhost;Database=TestDB;Trusted_Connection=true;Encrypt=False;";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            string sql = "SELECT Id, Name FROM Users";
            using (SqlCommand command = new SqlCommand(sql, connection))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Console.WriteLine($"Id: {reader["Id"]}, Name: {reader["Name"]}");
                    }
                }
            }
        }
    }
}

4. 异步查询(推荐用于 Web 应用)

避免阻塞线程,使用异步方法:

static async Task QueryAsync()
{
    string connectionString = "Server=localhost;Database=TestDB;Trusted_Connection=true;Encrypt=False;";
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
        string sql = "SELECT Id, Name FROM Users";
        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            using (SqlDataReader reader = await command.ExecuteReaderAsync())
            {
                while (await reader.ReadAsync())
                {
                    Console.WriteLine($"Id: {reader["Id"]}, Name: {reader["Name"]}");
                }
            }
        }
    }
}

5. 处理异常和连接安全

实际开发中要捕获异常并确保连接正确释放:

始终使用
using
语句确保资源释放
捕获
SqlException
处理数据库错误
不要在代码中硬编码密码,使用配置或密钥管理工具

基本上就这些。只要配置好连接字符串并正确使用 SqlClient 类库,.NET 可以轻松连接和查询 SQL Server。不复杂但容易忽略细节,比如关闭连接或处理空值。

相关推荐