参数化查询类似 [英] Parameterized query for like
本文介绍了参数化查询类似的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请给我一个参数化查询的解决方案赞在sql查询中匹配
我试过的:
Please give me the solution of parameterized query for "Like" Matching in sql query
What I have tried:
private void TxtSearch_TextChanged(object sender, EventArgs e)
{
try
{
con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\DATABASE\data.sql.mdf;Integrated Security=True;Connect Timeout=30");
con.Open();
// SqlCommand sda = new SqlCommand(" select * from Tab Where [Part_No] like '%@Part_No%' and [Company_Name] like '%@Company_Name%'", con);
//sda.Parameters.Clear();
sda.Parameters.AddWithValue("Part_No", TxtSearch.Text );
sda.Parameters.AddWithValue("Company_Name", TextBox1.Text );
con.Open();
dt = new DataTable("Tab");
adpt.Fill(dt);
DataGridView.DataSource = dt;
con.Close();
if (dt.Rows.Count <= 0)
{
DataRow row1 = dt.NewRow();
row1[0] = "No Record Found";
dt.Rows.Add(row1);
DataGridView.Rows[0].DefaultCellStyle.BackColor = Color.Yellow;
DataGridView.DefaultCellStyle.Font = new Font("Regular", 12, FontStyle.Regular);
}
else
{
DataGridView.Rows[0].DefaultCellStyle.BackColor = Color.Red;
DataGridView.DefaultCellStyle.Font = new Font("Regular", 12, FontStyle.Regular);
}
if (TextBox1.Text == "" && TxtSearch.Text == "")
{
con.Open();
adpt = new SqlDataAdapter(" select * from Tab ", con);
dt = new DataTable("Tab");
adpt.Fill(dt);
DataGridView.DataSource = dt;
con.Close();
}
}
catch
{
MessageBox.Show("Please Enter Proper Value");
}
}
推荐答案
使用
Use
select * from Tab Where [Part_No] like '%'+@Part_No+'%' and [Company_Name] like '%'+@Company_Name+'%'
或用百分比字符括起参数值:
or enclose the parameter values with the percentage characters:
SqlCommand sda = new SqlCommand(" select * from Tab Where [Part_No] like @Part_No and [Company_Name] like @Company_Name", con);
sda.Parameters.AddWithValue("Part_No", "%" + TxtSearch.Text + "%");
sda.Parameters.AddWithValue("Company_Name", "%" + TextBox1.Text + "%");
在参数化查询中使用SQLIN() - Microsoft:ASP.NET - Tek-Tips [ ^ ]
Morteza Sahragard - 在参数化查询中使用Like运算符 [ ^ ]
这篇关于参数化查询类似的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文