简体   繁体   中英

SQL Update command error in ExecuteNonQuery

When i try to connect to my database to Edit a datatable in 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.

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

  1. The syntax for UPDATE is incorrect. It should be UPDATE SET columnName = value...
  2. Use parameterised queries, because at the moment your code is vulnerable to SQL injection
  3. Move myCommand.ExecuteNonQuery(); inside the try block to catch any exceptions

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM