c#sql server链接数据库
时间: 2024-12-06 14:20:31 浏览: 21
在 C# 中,连接 SQL Server 数据库通常通过ADO.NET(ActiveX Data Objects for .NET Framework)来完成,这是 .NET 平台上用于访问各种数据源的标准方式。以下是基本步骤:
1. 引入命名空间:
```csharp
using System.Data.SqlClient;
```
2. 创建 SqlConnection 对象:
```csharp
string connectionString = "Data Source=服务器地址;Initial Catalog=数据库名;User ID=用户名;Password=密码;";
SqlConnection connection = new SqlConnection(connectionString);
```
确保替换上述代码中的 `服务器地址`、`数据库名`、`用户名` 和 `密码` 为你实际的数据库配置。
3. 打开连接:
```csharp
connection.Open();
```
4. 执行 SQL 查询或操作(例如,使用 SqlCommand 类创建SqlCommand 对象并执行命令):
```csharp
SqlCommand command = new SqlCommand("SELECT * FROM 表名", connection);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 读取结果并处理
}
reader.Close();
connection.Close(); // 关闭连接后记得释放资源
```
5. 使用完毕后关闭 SqlDataReader 和 SqlConnection。
阅读全文
相关推荐










