拼接多条件SQL思维
时间:2021-07-01 10:21:17
帮助过:24人阅读
private void button1_Click(
object sender, EventArgs e)
2 {
3 StringBuilder sbSql =
new StringBuilder(
"select * from student ");
4 List<
string> wheres =
new List<
string>
();
5 List<SqlParameter> parameters =
new List<SqlParameter>
();
6 foreach (Control ct
in panel1.Controls)
//遍历容器中的集合
7 {
8 //这里只介绍一种思维方式,具体逻辑还需改造方法
9 if (ct
is TextBox)
//文本框
10 {
11 wheres.Add(
" "+ct.Name+
" like @"+ct.Name+
" ");
//ct.Name:获取控件的Name属性,必须有命名规则,和数据库字段相同
12 parameters.Add(
new SqlParameter(
"@"+ct.Name+
"",
"‘%"+ct.Text.Trim()+
"%‘"));
13 continue;
14 }
15 if (ct
is CheckBox)
16 {
17 //复选框
18 }
19 if (ct
is DateTimePicker)
20 {
21 //日期控件
22 }
23 if (ct
is ComboBox)
24 {
25 //下拉框
26 }
27 }
28 //开始多条件搜索拼接
29 if (wheres.Count>
0)
//有值
30 {
31 sbSql.Append(
" where ");
32 sbSql.Append(
string.Join(
" and ",wheres.ToArray()));
//调用字符串连接 string.Join
33 }
34 MessageBox.Show(sbSql.ToString());
//多条件拼接SQL成功!
35 }
拼接多条件SQL思维
标签:trim 代码 mes click str show 文本 情况 bsp