如何在C#中的Sql Server中将参数与LIKE一起使用 [英] How to use parameter with LIKE in Sql Server in C#

查看:82
本文介绍了如何在C#中的Sql Server中将参数与LIKE一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,
我正在尝试使用C#编写查询以在sql表中进行搜索.
sql查询

Hi everyone ,
I am trying to write a query in C# to search in the sql table.
the sql query

SELECT *
FROM Customer
WHERE FirstName LIKE '%34%'
or LastName LIKE '%Appiah%'
Or State LIKE '%OH%';




在C#中,我希望它在文本框中搜索内容.
前任.喜欢%textBox.text%
但是我不知道怎么写.




in C# i want it to search for what inside the textbox .
ex. LIKE %textBox.text%
but i don''t know how to write it.

推荐答案

如果您正在使用LINQ(它将与EntityFramework一起使用),那么您将想使用类似于string.Contains.在LINQ中使用扩展方法:

If you are looking at using LINQ (which would be used with EntityFramework), then would want to use something like string.Contains. Using extension methods with LINQ:

var x = Customer.Where(i => i.FirstName.Contains(x) || i.LastName.Contains(y) || i.State.Contains(z))



如果要精确匹配,则应使用等于的"=="运算符.也可以创建一个RegEx表达式.如上所述,由于使用SQL注入,通常不赞成直接使用SQL语句.

可能的另一种选择是创建一个SQL过程,该过程接受FirstName,LastName和State的参数,并返回与请求匹配的记录.



If you want exact matches then would use the equal "==" operator instead. Can also created a RegEx expression. As stated above, using SQL statement directly is generally frowned upon because of SQL injection.

What might be another option is to create a SQL proceedure that takes the arguments for FirstName, LastName, and State, and returns those records matching the request.


字符串sql =("SELECT * FROM Customer WHERE(FirstName LIKE \''%"+(txtSearch.Text +"%\'')));
string sql = ("SELECT * FROM Customer WHERE (FirstName LIKE \''%" + (txtSearch.Text + "%\'')"));


这篇关于如何在C#中的Sql Server中将参数与LIKE一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆