asp.net Parameters.AddWithValue方法在SQL语句的 Where 字句中的用法
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();