[英]Retrieve some data from database
I want to retrieve some data from the database and I have a problem 我想从数据库中检索一些数据,但是我遇到了问题
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["homeworkConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, FileName, Date from tblFiles where CourseName LIKE '%' + TextBox3.Text + '%'"; ;
cmd.Connection = con;
con.Open();
GridView1.DataBind();
con.Close();
}
}
}
The textbox3 have that data 文本框3具有该数据
So the problem I thank is with "LIKE" ? 因此,我要感谢的问题是“ LIKE”吗?
I changed it to: 我将其更改为:
private void BindGrid()
{
string likeCondition = string.Empty;
string textBoxContent = TextBox3.Text;
var splittedContents = textBoxContent.Split(',').ToList();
int index = 0;
foreach (var splittedContent in splittedContents)
{
likeCondition += "CourseName LIKE %" + splittedContent + "%";
index++;
if (index != splittedContent.Length)
likeCondition += " OR ";
}
string constr = ConfigurationManager.ConnectionStrings["homeworkConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Id, FileName, Date from tblFiles where " + likeCondition; ;
cmd.Connection = con;
con.Open();
GridView1.DataBind();
con.Close();
}
}
}
but it still is not working - what do I have to do? 但它仍然无法正常工作-我该怎么办?
cmd.CommandText = "select Id, FileName, Date from tblFiles where CourseName LIKE '%' + TextBox3.Text + '%'"
your string is using the literal textbox name. 您的字符串使用文字文本框名称。
you want something like 你想要类似的东西
cmd.CommandText = "select Id, FileName, Date from tblFiles where CourseName LIKE '%" + TextBox3.Text + "%'"
however, you'd be better off with paramatized queries 但是,使用参数化查询会更好
cmd.CommandText = "select Id,Name from tblName where Name LIKE '%" + TextBox1.Text + "%'"
You need to split up your TextBox3
content with respect to ,
and build your whole like condition. 您需要针对拆分您的TextBox3
内容,
并构建您的整体条件。
I would do it in following way : 我会以以下方式做到这一点:
string likeCondition = string.Empty;
string textBoxContent = "Programming1,Database";// use TextBox3.Text here
var splittedContents = textBoxContent.Split(',').ToList();
int index = 0;
foreach (var splittedContent in splittedContents)
{
likeCondition += "CourseName LIKE %" + splittedContent + "%";
index++;
if (index != splittedContent.Length)
likeCondition += " OR ";
}
Now, you should use above likeCondition
in your query in following way : 现在,您应该通过以下方式在查询中使用上述likeCondition
:
cmd.CommandText = "select Id, FileName, Date from tblFiles where " + likeCondition; ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.