C#中怎么对sqlserver进行增删查改操作
时间: 2024-11-25 08:16:34 浏览: 30
在C#中,使用ADO.NET(ActiveX Data Objects for .NET)库进行SQL Server的数据访问是非常常见的。以下是一个简单的例子来展示如何执行基本的增删查改操作:
1. **连接数据库**:
首先,你需要创建一个`SqlConnection`对象来代表到数据库的连接。例如:
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
// 连接字符串包含你的数据库信息
}
```
2. **打开连接**:
```csharp
connection.Open();
```
3. **执行查询(读取)**:
使用`SqlCommand`执行SELECT查询:
```csharp
string sql = "SELECT * FROM Customers WHERE ID = @id";
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("@id", id);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["Name"]);
}
```
4. **插入数据(增加)**:
对于INSERT,可以这样做:
```csharp
sql = "INSERT INTO Products (Name, Price) VALUES (@name, @price)";
SqlCommand insertCommand = new SqlCommand(sql, connection);
insertCommand.Parameters.AddWithValue("@name", productName);
insertCommand.Parameters.AddWithValue("@price", productPrice);
int rowsAffected = insertCommand.ExecuteNonQuery();
```
5. **更新数据(修改)**:
```csharp
sql = "UPDATE Customers SET Email = @email WHERE ID = @id";
SqlCommand updateCommand = new SqlCommand(sql, connection);
updateCommand.Parameters.AddWithValue("@email", newEmail);
updateCommand.Parameters.AddWithValue("@id", customerId);
rowsAffected = updateCommand.ExecuteNonQuery();
```
6. **删除数据(删除)**:
```csharp
sql = "DELETE FROM Products WHERE ProductID = @id";
SqlCommand deleteCommand = new SqlCommand(sql, connection);
deleteCommand.Parameters.AddWithValue("@id", productId);
rowsAffected = deleteCommand.ExecuteNonQuery();
```
7. **关闭连接**:
执行完所有操作后别忘了关闭资源:
```csharp
reader.Close();
connection.Close();
```
记得处理异常,并在实际应用中使用try-catch块来管理可能出现的问题。
阅读全文