作者:mobiledu2502922357 | 来源:互联网 | 2022-03-06 03:57
string strField = "id|className|classAdd";
string strKeyWords = this.tbxKeyWords.Text.Trim();
string strSql = dbexe.searchText("select * from class", strField, strKeyWords);
经常用到多字段的模糊查询,上面的函数可以实现,例如strKeyWords值为“”时,可以输出:
select * from class where id like '%%' or className like '%%' or classAdd like '%%'
函数:
///
/// 根据关键字实现多字段模糊查询
/// ///
select * from talbe sql语句
///
判断语句条件,是一个用|隔开的字符串
///
关键字
public static string searchText(string strSql, string strField, string keywords)
{
StringBuilder sb = new StringBuilder(strSql);
if (strField != string.Empty)
{
sb.Append(" where ");
string[] arrKey = strField.Split('|');
for (int i = 0; i < arrKey.Length; i++)
{
sb.Append(arrKey[i] + " like '%" + keywords + "%' or ");
}
string str = sb.ToString();
//去除最后一个"or"
if (str.IndexOf("or") >= 0)
{
return str.Remove(str.LastIndexOf("or"));
}
return str;
}
return strSql;
}