通常写一个简单的模糊查询的SQL语句格式可以如下例: 说明:1、WHERE 关键词的后面跟着用来过滤数据的条件,百分号%是通配符,可以代表多个任何字符,若是下划线_就代表一个任意字符。 实例如下: sql="select * from 表名 where 姓名 like ’%"&request.form("name")&"%’ and 性别 like ’%"&request.form("sex")&"%’ and 电话 like ’%"&request.form("call")&"%’ " 上面这条SQL语句使用了三个模糊查询条件:姓名、性别、电话,当然我们还可以用类似 的方式构造更多的条件。
下面看一个实例:
///模糊查询实例/ using System; using System.Data; using System.Data.SqlClient; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Search : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } private string getSafestring(string s) { s = s.Trim(); s = s.Replace("'","''"); s = s.Replace("\"", ""); s = s.Replace("%", ""); s = s.Replace("--", ""); s = s.Replace(";", ""); s = s.Replace("(", ""); s = s.Replace(")", ""); s = s.Replace("-", ""); return s; } protected void ImageButton1_Click(object sender, ImageClickEventArgs e) { ConnectionFactory cf = new ConnectionFactory(); string sql = "select * from v_topic"; string key = ""; if (TextBox1.Text != "") key = "topicname like '%" + getSafestring(TextBox1.Text) + "%'"; if (Checkshowhide.Checked) { if (TextBox2.Text != "") { if (key == "") key = "uid like '%" + getSafestring(TextBox2.Text) + "%'"; else key += " and uid like '%" + getSafestring(TextBox2.Text) + "%'"; } if (RadioButton2.Checked) { if (key == "") key = "state=1"; else key += " and state=1"; } if (RadioButton3.Checked) { if (key == "") key = "state=2"; else key += " and state=2"; } if (DropDownList1.SelectedItem.Text != "全部时间") { if (RadioButton4.Checked) { if (key == "") key = "emittime > '" + DateTime.Now.AddDays(-int.Parse(DropDownList1.SelectedValue)) + "'"; else key += " and emittime > '" + DateTime.Now.AddDays(-int.Parse(DropDownList1.SelectedValue)) + "'"; } else { if (key == "") key = "emittime < '" + DateTime.Now.AddDays(-int.Parse(DropDownList1.SelectedValue)) + "'"; else key += " and emittime < '" + DateTime.Now.AddDays(-int.Parse(DropDownList1.SelectedValue)) + "'"; } } if (RadioButton6.Checked) { key += " order by " + DropDownList2.SelectedValue; } else { key += " order by " + DropDownList2.SelectedValue + " desc"; } } if (key != "") sql += " where " + key; GridView1.DataSource = cf.getTable(sql); GridView1.DataBind(); Label7.Visible = true; Label7.Text = "共找到符合条件的数据" + GridView1.Rows.Count + "条"; Checkshowhide.Checked = false; } }
asp.net+SQL2005实现字符串的模糊查询
最新推荐文章于 2021-12-07 11:11:33 发布