这个搜索查询有什么问题? [英] Whats wrong with this search query?
本文介绍了这个搜索查询有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
protected void btnSearch_Click(对象发件人,EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings [ constr]。ConnectionString;
con.Open();
尝试
{
字符串 query = select * from news where name like + txtSearch.Text + %'或描述如' + txtSearch.Text + %';
SqlCommand cmd = new SqlCommand(query,con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gridrecord.DataSource = ds;
gridrecord.DataBind();
if (gridrecord.Rows.Count == 0 )
{
lblmsg.Visible = true ;
lblmsg.Text = 未找到数据;
}
}
catch (例外情况)
{
}
}
解决方案
}
catch (Exception ex)
{
}
这是错的:你吞下任何异常,因此你没有机会摆脱错误。
另外,如果发生异常,你不会关闭连接。我建议使用using指令:
使用(SqlConnection con = new SqlConnection())
{
con.ConnectionString = ... etc.
}
和
if (gridrecord.Rows.Count == 0 )
{
lblmsg.Visible = true ;
lblmsg.Text = 未找到数据;
}
在上次失败后查询成功时永远不会重置该标签。
在使用Like Query时更好地使用Trim()来避免空间
string query = 从新闻中选择*,其中名称为 + txtSearch。文字 .Trim()+ %'或描述如 + txtSearch。 Text .Trim()+ %';
protected void btnSearch_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
con.Open();
try
{
string query = "select * from news where name like '" + txtSearch.Text + "%' or description like '" + txtSearch.Text + "%' ";
SqlCommand cmd = new SqlCommand(query, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
con.Close();
gridrecord.DataSource = ds;
gridrecord.DataBind();
if (gridrecord.Rows.Count == 0)
{
lblmsg.Visible = true;
lblmsg.Text = " No data found";
}
}
catch (Exception ex)
{
}
}
解决方案
} catch (Exception ex) { }
That's wrong: you swallow any exception, hence you have no chance to get rid of the error.
Also, you do not close the connection in case of an exception. I suggest a using directive:
using(SqlConnection con = new SqlConnection()) { con.ConnectionString = ... etc. }
And
if (gridrecord.Rows.Count == 0) { lblmsg.Visible = true; lblmsg.Text = " No data found"; }
will never reset that label when a query succeeds after a previous failure.
better you use Trim() to Avoid Space while using Like Query
string query = "select * from news where name like '" + txtSearch.Text.Trim() + "%' or description like '" + txtSearch.Text.Trim() + "%' ";
这篇关于这个搜索查询有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文