我使用这段 dynamicSQL 代码。
问题是,当我在运行时检查 cmd.CommandText 值时,@ID_USER 和 @SEARCH 在 SQL 查询中保持原始状态,它读取
"SELECT Comment FROM Comments WHERE UserId = @ID_USER AND Comment like '% @SEARCH %'"
所以语法是正确的,并且 cmd.Parameters ResultView .SqlValuein VS2012 为我提供了@USER_ID 和@SEARCH 的正确输入值谢谢。
{
List<string> searchResults = new List<string>();
//Get current user from default membership provider
MembershipUser user = Membership.Provider.GetUser(HttpContext.User.Identity.Name, true);
if (user != null)
{
if (!string.IsNullOrEmpty(searchData))
{
// SqlCommand cmd = new SqlCommand("Select Comment from Comments where UserId = '" + user.ProviderUserKey + "' and Comment like '%" + searchData + "%'", _dbConnection);
/**********************************************/
_dbConnection.Open();
const string QUERY =
@"SELECT Comment" +
@" FROM Comments" +
@" WHERE UserId = @ID_USER" +
@" AND Comment like '% @SEARCH %'";
var cmd = new SqlCommand(QUERY, _dbConnection);
cmd.Parameters.AddWithValue("@ID_USER", user.ProviderUserKey.ToString());
cmd.Parameters.AddWithValue("@SEARCH", searchData.ToString());
/**********************************************/
SqlDataReader rd = cmd.ExecuteReader();
while (rd.Read())
{
searchResults.Add(rd.GetString(0));
}
rd.Close();
_dbConnection.Close();
}
}
return View(searchResults);
}