本文介绍了在C#编程语言中如何有效地使用SqlParameter对象来执行数据库操作,包括添加、配置和使用SQL参数的方法。
C#中的SqlParameter参数写法示例如下:
1. 创建一个新的 SqlParameter 对象,并设置其属性。
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(SELECT * FROM Employees WHERE EmployeeID = @EmpID, connection);
command.Parameters.Add(@EmpID, SqlDbType.Int).Value = 1;
// 执行查询或其他操作
}
```
2. 使用 SqlParameter 构造函数创建参数,并直接设置值。
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(INSERT INTO Employees (Name, Position) VALUES (@Name, @Position), connection);
// 添加参数并赋值
command.Parameters.Add(new SqlParameter(@Name, John Doe));
command.Parameters.Add(new SqlParameter(@Position, Developer));
// 执行插入或其他操作
}
```
3. 使用 AddWithValue 方法简化添加和设置参数的过程。
```csharp
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(UPDATE Employees SET Name=@Name WHERE EmployeeID=@EmpID, connection);
// 添加并赋值参数,使用 AddWithValue 方法
command.Parameters.AddWithValue(@Name, Jane Doe);
command.Parameters.AddWithValue(@EmpID, 2);
// 执行更新或其他操作
}
```
以上是 C# 中处理 SqlParameter 参数的一些常见写法。根据具体需求选择合适的用法即可。