欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net Parameters.AddWithValue方法在SQL语句的 Where 字句中的用法

程序员文章站 2023-11-18 22:29:46
他的写法是这样的: 复制代码 代码如下:view plaincopy to clipboardprint? string strwhere = "'%美%'"; strsq...

他的写法是这样的:

复制代码 代码如下:

view plaincopy to clipboardprint?
string strwhere = "'%美%'";
strsql = "select * from area where [name] like @strwhere";//这个就不好使
cmd.parameters.addwithvalue("@strwhere", strwhere);
string strwhere = "'%美%'";
strsql = "select * from area where [name] like @strwhere";//这个就不好使
cmd.parameters.addwithvalue("@strwhere", strwhere);

这是因为,asp.net在生成sql语句时,会在like后面再加上一次单引号,造成错误,如果打开 sql server的跟踪管理器,可以看到执行的语句如下
复制代码 代码如下:

exec sp_executesql n'select * from article where [title] like @strwhere',n'@strwhere nvarchar(5)',@strwhere=n'%为什么%'

不难理解,在 olddbcommand 中也会有类似的做法。
正确的代码为:
复制代码 代码如下:

string connectionstring = @"provider=microsoft.jet.oledb.4.0;data source=|datadirectory|\aspxweb.mdb;";
oledbconnection con = new oledbconnection(connectionstring);
con.open();
oledbcommand cmd = new oledbcommand();
cmd.connection = con;
string strwhere = "%孟宪会%";
string strsql = "select * from document where [author] like @strwhere";
cmd.parameters.addwithvalue("@strwhere", strwhere);
cmd.commandtext = strsql;
oledbdatareader dr = cmd.executereader();
while (dr.read())
{
response.write(dr["author"] + " : " + dr["title"] + "<br>");
}
con.close();
con.dispose();