c# sqlparameter
时间: 2023-10-28 18:05:53 浏览: 42
C# SqlParameter 是一种用于向 SQL 查询或存储过程中传递参数的对象。它可以帮助我们避免 SQL 注入攻击,提高应用程序的安全性。下面是一个简单的示例:
```csharp
string sql = "SELECT * FROM Customers WHERE Country = @Country";
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@Country", "USA");
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine(reader["CustomerName"]);
}
reader.Close();
}
}
```
在这个示例中,我们首先定义了一个 SQL 查询语句,并使用 @Country 占位符来代替实际的参数值。然后,我们创建一个 SqlConnection 和一个 SqlCommand 对象,并将查询语句和连接对象作为参数传递给 SqlCommand 构造函数。接着,我们使用 AddWithValue 方法向 SqlCommand 对象添加一个 SqlParameter 对象,它的名称为 "@Country",值为 "USA"。最后,我们打开连接,执行查询,并读取结果集中的数据。
使用 SqlParameter 不仅可以避免 SQL 注入攻击,还可以提高查询性能和可读性。它可以自动将参数值转换为正确的数据类型,并且可以在不修改查询语句的情况下更改参数值。