WHERE
子句结合逻辑运算符(如
AND
)连接两个条件即可。
在C#中,进行数据库查询时,如果需要根据两个条件来筛选数据,可以使用多种方式编写查询语句,以下是几种常见的方法:
1、使用参数化查询:这是一种推荐的方式,可以避免SQL注入攻击,提高代码的安全性和可维护性,以下是一个示例,假设我们有一个名为Users
的表,包含UserID
、Username
和Age
等列,我们要查询年龄大于20且用户名以字母“A”开头的用户:
using System; using System.Data.SqlClient; class Program { static void Main() { string connectionString = "your_connection_string_here"; string query = "SELECT * FROM Users WHERE Age > @Age AND Username LIKE @UsernamePattern"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(query, connection); command.Parameters.AddWithValue("@Age", 20); command.Parameters.AddWithValue("@UsernamePattern", "A%"); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine("UserID: " + reader["UserID"].ToString()); Console.WriteLine("Username: " + reader["Username"].ToString()); Console.WriteLine("Age: " + reader["Age"].ToString()); Console.WriteLine(); } reader.Close(); } } }
在这个示例中,我们使用了SqlParameter
对象来传递参数,这样可以确保参数的值被正确地传递给SQL查询,并且避免了直接拼接字符串可能带来的安全问题。
2、使用字符串拼接(不推荐):虽然可以使用字符串拼接的方式来构建查询语句,但这种方式存在SQL注入的风险,因此不推荐使用,以下是一个示例:
using System; using System.Data.SqlClient; class Program { static void Main() { string connectionString = "your_connection_string_here"; int age = 20; string usernamePattern = "A%"; string query = "SELECT * FROM Users WHERE Age > " + age + " AND Username LIKE '" + usernamePattern + "'"; using (SqlConnection connection = new SqlConnection(connectionString)) { SqlCommand command = new SqlCommand(query, connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { Console.WriteLine("UserID: " + reader["UserID"].ToString()); Console.WriteLine("Username: " + reader["Username"].ToString()); Console.WriteLine("Age: " + reader["Age"].ToString()); Consoles.WriteLine(); } reader.Close(); } } }
3、使用LINQ to SQL(Entity Framework):如果你使用的是Entity Framework等ORM框架,可以通过LINQ来编写更加简洁和类型安全的查询语句,以下是一个示例:
using System; using System.Linq; class Program { static void Main() { using (MyEntities context = new MyEntities()) { var users = from u in context.Users where u.Age > 20 && u.Username.StartsWith("A") select u; foreach (var user in users) { Console.WriteLine("UserID: " + user.UserID); Console.WriteLine("Username: " + user.Username); Console.WriteLine("Age: " + user.Age); Console.WriteLine(); } } } }
在上述代码中,MyEntities
是Entity Framework生成的上下文类,Users
是对应的实体集合,通过LINQ查询,我们可以方便地筛选出符合条件的用户。
在实际开发中,建议优先使用参数化查询或ORM框架提供的查询方式,以确保代码的安全性和可维护性。