多条件查询

 1 private void button1_Click(object sender, EventArgs e)
 2         {
 3             StringBuilder sql =new StringBuilder("select * from tblBook");
 4             List<string> list=new List<string>();
 5             List<SqlParameter> listspt = new List<SqlParameter>();
 6             if(textBox1.Text.Trim().Length>0)
 7             {
 8                 list.Add("title like '@title'");
 9                 SqlParameter spt = new SqlParameter("@title","%"+ textBox1.Text.Trim()+"%");
10                 listspt.Add(spt);
11                 //sql.Append("title=@title");
12             }
13             if (textBox2.Text.Trim().Length > 0)
14             {
15                 list.Add("public like '@public'");
16                 SqlParameter spt = new SqlParameter("@public","%"+ textBox2.Text.Trim()+"%");
17                 listspt.Add(spt);
18                 //sql.Append("public=@public");
19             }
20             if (textBox3.Text.Trim().Length > 0)
21             {
22                 list.Add("author like '@author'");
23                 SqlParameter spt = new SqlParameter("@author","%"+ textBox3.Text.Trim()+"%");
24                 listspt.Add(spt);
25                 //sql.Append("anthor=@anthor");
26             }
27             if (list.Count > 0)
28             {
29                 sql.Append(" where "+string.Join(" and ",list.ToArray()));
30             }
31             MessageBox.Show(sql.ToString());
32         }
View Code

 

posted @ 2013-12-06 18:54  搞IT的蟋蟀  阅读(130)  评论(0)    收藏  举报