2013-07-25 59 views
1

這些是我的函數來更新SQL記錄庫中的學生記錄和插入學生記錄。
插入函數插入SQL表中的記錄正常工作,但更新函數更新記錄不能正常工作

public void UpdateStudent(ref student stu, string rollno) //Update the values to corresponding roll number 'rollno' 
     { 
      try 
      { 
       connection.Open(); //I have already defined the connection and command 
       command = new SqlCommand("update student set FirstName='"+stu.Firstname+"',LastName='"+stu.Lastname+"',YearOfAdmission="+stu.Yearofadmission+",Branch='"+stu.Branch+"' where RollNo='"+rollno+"'", connection); //Yearofadmission is int 
       command.ExecuteNonQuery(); 

     } 
     catch (Exception) 
     { 
      throw; 
     } 
     finally 
     { 
      if (connection != null) 
       connection.Close(); 
     } 
    } 
public void insertstudent(ref student s) 
     {    
      try 
      { 
       connection.Open(); 
       command = new SqlCommand("insert into student values('"+s.Rollno+"','"+ s.Firstname+"','"+s.Lastname+"',"+s.Yearofadmission+",'"+s.Branch+"','"+s.Password+"')", connection);     
       command.ExecuteNonQuery(); 

      } 
      catch (Exception) 
      { 
       throw;   
      } 
      finally 
      { 
       if (connection != null) 
        connection.Close(); 
      } 
     } 

我的第二個功能「insertstudent」插入值到SQL表工作正常並正確插入值到數據庫表。但第一個功能'更新學生'沒有更新數據庫表中的值。它也沒有提供任何錯誤。 所以我錯了?


在此先感謝!

+0

您應該使用命名參數而不是連接sql字符串。 –

+0

嘗試捕獲更新中生成的SQL,並在Management Studio中運行它,看看它做了什麼..看起來像你的過濾器rollno不是以某種方式匹配的。 – AJP

+0

確保切換到sql參數!如果你真的想看到這個問題,我會在那裏放置一個斷點並進行調試。比檢查你的命令,看看它在做什麼。但是,是的,廢除代碼並切換到http://www.dotnetperls.com/sqlparameter –

回答

0

檢查以確保傳遞給更新函數的rollno是正確的。如果該命令沒有拋出錯誤,則很可能它正在正確執行並最終沒有更新,因爲沒有記錄觸及提供的rollno。

在更新函數開始處設置一個斷點並檢查提供的rollno值。

另外,在你的插入語句中是's'的一個子集,而在update中,它是單獨提供的,你可能需要檢查是否可以。

0

使用參數的正確方法。您還需要處理連接和命令對象。

using (connection = new SqlConnection("connectionstring")) 
    { 
    using (command = connection.CreateCommand()) 
    { 
    command.CommandText = "update student set FirstName= @FirstName ,LastName= @LastName, YearOfAdmission= @YearOfAdmission, [email protected] WHERE RollNo= @RollNo"; 

    command.Parameters.AddWithValue("@FirstName", stu.FirstName); 
    command.Parameters.AddWithValue("@LastName", stu.LastName); 
    command.Parameters.AddWithValue("@YearOfAdmission", stu.YearOfAdmission); 
    command.Parameters.AddWithValue("@Branch", stu.Branch); 
    command.Parameters.AddWithValue("@RollNo", stu.RollNo); 

     connection.Open(); 

        command.ExecuteNonQuery(); 
    connection.Close(); 
    } 
    } 
+0

這兩種方式有何不同?請讓我知道這.. – ash

+0

從安全角度來看,使用命名參數可防止SQL注入。從易用性的角度來看,你不需要做自己的字符串連接,而且它的代碼更具可讀性。 –

+0

我明白了..謝謝! – ash