我正在尝试计算表AUTHORIZED_USERS中存在登录用户ID的实例数。我查找的值在UNAME字段中找到,并且是包含以下格式的字符串:COMPANYNAME \ 111222333。如果表中存在该值,则表示用户有权访问应用程序/视图。否则,它们将被重定向到拒绝访问的页面。我的代码接近工作,但出现以下错误
Incorrect syntax near '\601011307'.
\ 601011307是表UNAME字段中包含的条目的一部分。它应该识别的全部值是COMPANYNAME \ 601011307。
如何防止此错误并将计数值分配给变量,以便我可以在条件中使用它?
public ActionResult HolidayDateTable()
{
string whoareyoupeople = User.Identity.Name.ToString();
DateTime date = DateTime.Now;
string myerrorstring = "User " + whoareyoupeople + " attempted unauthorized access on " + date + ".";
SqlConnection conn = new SqlConnection("Data Source=SWDB10DSQL;Initial Catalog=BillingUI;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
{
cmd.CommandText = string.Format("SELECT COUNT(*) FROM AUTHORIZED_USERS WHERE UNAME = "+whoareyoupeople+")");
int count = (int)cmd.ExecuteScalar();
if (count == 0)
{
return RedirectToAction("AccessDenied");
}
else
{
return View(db.HOLIDAY_DATE_TABLE);
}
}
}
答案 0 :(得分:7)
您必须删除右括号并将其用单引号括起来,如:
SELECT COUNT(*) FROM AUTHORIZED_USERS WHERE UNAME = '" + whoareyoupeople + "'";
但是你应该使用sql-parameters来防止sql-injection。
SELECT COUNT(*) FROM AUTHORIZED_USERS WHERE UNAME = @UNAME
// ...
cmd.Parameters.Add("@UNAME", SqlDbType.VarChar).Value = whoareyoupeople;
答案 1 :(得分:1)
您缺少用于包含文字字符串的引号 -
cmd.CommandText = string.Format("SELECT COUNT(*) FROM AUTHORIZED_USERS WHERE UNAME = '"+whoareyoupeople+"'");