Windows Forms多文本框数据库搜索逻辑错误修复求助
问题修复方案
你的核心问题是原代码只能单条件搜索,无法实现多条件同时校验——只要第一个非空条件匹配就执行搜索,完全忽略其他输入的条件。要实现多条件“且”逻辑的搜索,需要动态拼接SQL的WHERE子句,同时必须改用参数化查询避免SQL注入风险。
修复步骤与代码实现
- 动态构建查询条件:遍历所有输入控件,收集非空的查询条件,用
AND连接成完整的WHERE子句。 - 参数化查询:不再直接拼接字符串,改用SQL参数传递输入值,彻底杜绝注入攻击。
- 处理性别字段映射:将下拉框的文本(Male/Female)映射为数据库对应的数值(0/1)。
修改后的代码如下:
private void search_Click(object sender, EventArgs e) { List<string> conditions = new List<string>(); Dictionary<string, object> parameters = new Dictionary<string, object>(); // 收集姓名条件 if (!string.IsNullOrWhiteSpace(textBox_Name.Text)) { conditions.Add("NAME LIKE @Name"); parameters.Add("@Name", $"{textBox_Name.Text}%"); } // 收集姓氏条件 if (!string.IsNullOrWhiteSpace(textBox_Surname.Text)) { conditions.Add("SURNAME LIKE @Surname"); parameters.Add("@Surname", $"{textBox_Surname.Text}%"); } // 收集ID条件 if (!string.IsNullOrWhiteSpace(textBox_Id.Text)) { conditions.Add("ID LIKE @Id"); parameters.Add("@Id", $"{textBox_Id.Text}%"); } // 收集手机号条件 if (!string.IsNullOrWhiteSpace(textBox_Phone.Text)) { conditions.Add("PHONE LIKE @Phone"); parameters.Add("@Phone", $"{textBox_Phone.Text}%"); } // 收集邮箱条件 if (!string.IsNullOrWhiteSpace(textBox_Email.Text)) { conditions.Add("EMAIL LIKE @Email"); parameters.Add("@Email", $"{textBox_Email.Text}%"); } // 收集性别条件 if (!string.IsNullOrWhiteSpace(comboBox_Gender.Text)) { int genderValue = comboBox_Gender.Text == "Male" ? 0 : 1; conditions.Add("GENDER = @Gender"); parameters.Add("@Gender", genderValue); } // 生成最终SQL语句 string sql = "SELECT * FROM BILGILER"; if (conditions.Count > 0) { sql += " WHERE " + string.Join(" AND ", conditions); } else { MessageBox.Show("请输入搜索信息"); return; } // 执行带参数的查询 showDataWithParameters(sql, parameters); } // 需要新增/修改的参数化查询方法(示例) private void showDataWithParameters(string sql, Dictionary<string, object> parameters) { // 请替换为你的数据库连接字符串 using (SqlConnection conn = new SqlConnection("你的数据库连接字符串")) { conn.Open(); using (SqlCommand cmd = new SqlCommand(sql, conn)) { foreach (var param in parameters) { cmd.Parameters.AddWithValue(param.Key, param.Value); } SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); adapter.Fill(dt); dataGridView1.DataSource = dt; } } }
关键说明
- 多条件逻辑:所有非空的输入条件都会被加入WHERE子句,用
AND连接,确保只有同时满足所有条件的记录才会被返回。比如输入正确手机号+错误邮箱时,没有匹配的记录,DataGridView会为空。 - SQL注入防护:参数化查询避免了恶意输入破坏SQL语句的风险,这是生产环境必须遵守的安全规范。
- 空值处理:用
string.IsNullOrWhiteSpace替代!= "",能更严谨地过滤空白字符输入。
内容的提问来源于stack exchange,提问作者turkmen
相关产品推荐
相关产品推荐

