他的寫法是這樣的:
複製代碼 代碼如下: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();