答案:.NET通过Microsoft.Data.SqlClient连接SQL Server,使用SqlConnection、SqlCommand执行同步或异步查询。示例包含连接字符串配置、using语句资源管理、异常处理及推荐的异步操作方式,确保安全与性能。
.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。不复杂但容易忽略细节,比如关闭连接或处理空值。
以上就是.NET怎么连接并查询SQL Server数据库的详细内容,更多请关注php中文网其它相关文章!


