喜欢运算符sql查询 [英] like operator sql query

查看:86
本文介绍了喜欢运算符sql查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了查询:



 SqlCommand cmd = new SqlCommand(select * from profile where name LIKE+%+ TextBox1.Text +%,cnn); 





这会给我一个错误。这有什么问题?



=code-string> select from from profile where name LIKE + ' + TextBox1.Text + ',cnn);





您错过了一个空格(在LIKE旁边)和单引号(在%之前和之后)


如前面的解决方案所述,问题是缺少单引号。



但是,更正是要正确使用参数(参见 SqlParameter [ ^ ])。



所以代码应该像:

 SqlCommand cmd =  new  SqlCommand(  select * from profile where name LIKE @name,cnn); 
cmd.Parameters.Add( @ name,SqlDbType.VarChar, 100 )。值= 字符串 .Format( < span class =code-string>%{0}%,TextBox1.Text);
...



如果不使用参数,您将接受SQL注入,非法字符问题(例如单引号)等。


i have written query:

SqlCommand cmd = new SqlCommand("select * from profile where name LIKE" +"%"+TextBox1.Text+ "%" , cnn);



this will give me error.what is problem in this?

解决方案

Try changing that line to

SqlCommand cmd = new SqlCommand("select * from profile where name LIKE " +"'%"+TextBox1.Text+ "%'" , cnn);



You are missing a space (next to LIKE) and single quotes (before and after %)


As stated in the previous solution, the problem is the missing single quotes.

However, the correction is to properly use parameters (see SqlParameter[^]).

So the code should be something like:

SqlCommand cmd = new SqlCommand("select * from profile where name LIKE @name" , cnn);
cmd.Parameters.Add("@name", SqlDbType.VarChar, 100).Value = string.Format("%{0}%", TextBox1.Text);
...


Without using parameters, you will be open to SQL injections, illegal character problems (single quote for example) etc.


这篇关于喜欢运算符sql查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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