asp.net 代码如下
string strConn = "server=localhost;database=My;uid=sa;pwd=123456";
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
SqlParameter sp = new SqlParameter("@Keyword",SqlDbType.NVarChar,50);
sp.Value = "'"; // 这里假设查找包含单引号的文章
SqlCommand comm = new SqlCommand("SearchArticle",conn);
comm.CommandType=CommandType.StoredProcedure;
comm.Parameters.Add(sp);
DataGrid1.DataSource = comm.ExecuteReader();
DataGrid1.DataBind();
conn.Close();// 下面是SQL存储过程ALTER procedure SearchArticle
@Keyword NVARCHAR(50)
ASdeclare @sql nvarchar(1000)-- 这里必须要使用@sql变量字串做命令,不要改
set @sql = 'select * from article where title like ''%'+@Keyword+'%'''
exec(@sql) 为什么查找别的都正确,查“'” 单引号就错,错再哪里呢?? 采用命令参数应该可以自动处理单引号问题啊, 我想是存储过程错了吧。
string strConn = "server=localhost;database=My;uid=sa;pwd=123456";
SqlConnection conn = new SqlConnection(strConn);
conn.Open();
SqlParameter sp = new SqlParameter("@Keyword",SqlDbType.NVarChar,50);
sp.Value = "'"; // 这里假设查找包含单引号的文章
SqlCommand comm = new SqlCommand("SearchArticle",conn);
comm.CommandType=CommandType.StoredProcedure;
comm.Parameters.Add(sp);
DataGrid1.DataSource = comm.ExecuteReader();
DataGrid1.DataBind();
conn.Close();// 下面是SQL存储过程ALTER procedure SearchArticle
@Keyword NVARCHAR(50)
ASdeclare @sql nvarchar(1000)-- 这里必须要使用@sql变量字串做命令,不要改
set @sql = 'select * from article where title like ''%'+@Keyword+'%'''
exec(@sql) 为什么查找别的都正确,查“'” 单引号就错,错再哪里呢?? 采用命令参数应该可以自动处理单引号问题啊, 我想是存储过程错了吧。
因为'特殊字符.
@Keyword NVARCHAR(50)
ASdeclare @sql nvarchar(1000)-- 这里必须要使用@sql变量字串做命令,不要改
set @sql = 'select * from article where charindex('+@Keyword+',title)<>0'
exec(@sql)
把存储过程改成这样:ALTER procedure SearchArticle
@Keyword NVARCHAR(50)
ASSET @Keyword = REPLACE(@Keyword,'''','''''')
declare @sql nvarchar(1000)-- 这里必须要使用@sql变量字串做命令,不要改
set @sql = 'select * from article where title like ''%'+@Keyword+'%'''
exec(@sql)
SearchArticle '''''' 连着6个单引号
你的肯定没有6个。
------------------------------------------------
支持这种作法。那我要查找 包含“%” “[” “]” “_” 这些SQL中的关键字呢?怎么写? 都要存储过程判断一下吗
________________________________________________
不需要。
之所以对单引号进行处理是因为你的查询语句是通过拼接形成的,单引号会影响查询语句的结构;而其他字符([, ] , %)等都不会对语句的结构造成影响,所以不需要处理。