c# sql 多条件查询
时间: 2023-09-25 21:08:40 浏览: 66
在 C# 中,你可以使用 SQL 查询语句来实现多条件查询。以下是一个示例代码:
```csharp
using System;
using System.Data.SqlClient;
class Program
{
static void Main()
{
string connectionString = "Your_Connection_String";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
// 构建 SQL 查询语句,使用 WHERE 子句来指定多个条件
string sqlQuery = "SELECT * FROM YourTable WHERE Condition1 = @Value1 AND Condition2 = @Value2";
using (SqlCommand command = new SqlCommand(sqlQuery, connection))
{
// 设置参数值
command.Parameters.AddWithValue("@Value1", "SomeValue1");
command.Parameters.AddWithValue("@Value2", "SomeValue2");
// 执行查询并获取结果
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
// 处理查询结果
// 例如:Console.WriteLine(reader.GetString(0));
}
}
}
}
}
}
```
在上面的示例中,你需要将 `Your_Connection_String` 替换为你自己的数据库连接字符串,并将 `YourTable` 替换为你要查询的表名。`Condition1` 和 `Condition2` 是你要应用的多个查询条件,你可以根据需要修改它们。
然后,根据具体的需求,你可以处理查询结果,例如打印到控制台或者存储到变量中进行进一步处理。