这个搜索查询有什么问题?

编程入门 行业动态 更新时间:2024-10-25 12:24:17
本文介绍了这个搜索查询有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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() + "%' ";

更多推荐

这个搜索查询有什么问题?

本文发布于:2023-10-28 08:37:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1536119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有什么

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!