簡體   English   中英

ExecuteNonQuery 中的 SQL 更新命令錯誤

[英]SQL Update command error in ExecuteNonQuery

當我嘗試連接到我的數據庫以在 MVC 中編輯數據表時。 當我嘗試訪問我的視圖時,我在執行命令時出錯。 錯誤是:

System.Data.SqlClient.SqlException: '附近的語法不正確('。關鍵字 SET 附近的語法不正確。

但我無法弄清楚我的語法錯誤。 我是初學者,所以我仍在學習基礎。 如果有任何幫助,將不勝感激。 謝謝!。 這是我的代碼

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);
}

您的代碼有幾個問題

  1. UPDATE的語法不正確。 它應該是UPDATE SET columnName = value...
  2. 使用參數化查詢,因為目前您的代碼容易受到 SQL 注入
  3. 移動myCommand.ExecuteNonQuery(); try塊內捕獲任何異常

請參閱我對您的代碼的更新:

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());
}

正如評論中提到的,您應該真正在HttpPost方法中執行更新並在調用UpdateDataBase()之前驗證值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM