[英]SQL Update command error in ExecuteNonQuery
When i try to connect to my database to Edit a datatable in MVC.当我尝试连接到我的数据库以在 MVC 中编辑数据表时。 When I try to acces to my view i have an error when I execute my command.当我尝试访问我的视图时,我在执行命令时出错。 the error is:错误是:
System.Data.SqlClient.SqlException: 'incorrect syntax near ('. incorrect syntax near the kewword SET. System.Data.SqlClient.SqlException: '附近的语法不正确('。关键字 SET 附近的语法不正确。
but i can not figure out my syntax errors.但我无法弄清楚我的语法错误。 I am a Beginer so i am still learning the basis.我是初学者,所以我仍在学习基础。 It would be really grateful for any help.如果有任何帮助,将不胜感激。 Thanks!.谢谢!。 here is my code这是我的代码
private void UpdateDataBase(int EmailId, string userName, string title, string Email, string description)
{
var sqlstring = string.Format("UPDATE Email (Email, Description, UserName, Title) " +
"SET ('{0}', '{1}', '{2}', '{3}')", Email, description, userName, title +
"WHERE ID=" + EmailId);
var myConnection = getconection();
SqlCommand myCommand = new SqlCommand(sqlstring, myConnection);
myCommand.ExecuteNonQuery();
try
{
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public ActionResult Edit (int EmailId, string userName, string title, string Email, string description)
{
UpdateDataBase(EmailId, userName, title, Email, description);
return View("EmailData");
}
[HttpPost]
public ActionResult Edit (ModelTemplateEmail EditEmailData)
{
if (ModelState.IsValid)
{
return RedirectToAction("EmailData");
};
return View(EditEmailData);
}
There are a couple of problems with your code您的代码有几个问题
UPDATE
is incorrect. UPDATE
的语法不正确。 It should be UPDATE SET columnName = value...
它应该是UPDATE SET columnName = value...
myCommand.ExecuteNonQuery();
移动myCommand.ExecuteNonQuery();
inside the try
block to catch any exceptions在try
块内捕获任何异常Please see my update to your code:请参阅我对您的代码的更新:
var sqlstring = @"UPDATE Email SET Email = @email, Description = @description, UserName = @username, Title = @title WHERE ID = @id");
var myConnection = getconection();
SqlCommand myCommand = new SqlCommand(sqlstring, myConnection);
// add parameters
myCommand.Parameters.AddWithValue("@email", email);
myCommand.Parameters.AddWithValue("@description", description);
myCommand.Parameters.AddWithValue("@username", userName);
myCommand.Parameters.AddWithValue("@title", title);
myCommand.Parameters.AddWithValue("@id", emailId);
try
{
// execute the command in the try block to catch any exceptions
myCommand.ExecuteNonQuery();
myConnection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
As mentioned in the comments, you should really perform the update in the HttpPost
method and validate the values before calling UpdateDataBase()
.正如评论中提到的,您应该真正在HttpPost
方法中执行更新并在调用UpdateDataBase()
之前验证值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.