2014-03-25 61 views
-1

我有一個數據庫,一個簡單的存儲過程被稱爲AddNewStudent:存儲過程不插入到表

CREATE PROCEDURE dbo.AddNewStudent(
    @fName nvarchar(20), 
    @sName nvarchar(20), 
    @lName nvarchar(20), 
    @faculty nvarchar(10), 
    @specialty nvarchar(50), 
    @OKS smallint, 
    @StudentStat smallint, 
    @fak nvarchar(50), 
    @Course smallint, 
    @Porok nvarchar(5), 
    @Group int 
    ) 
    AS 
    INSERT INTO [Students] (FirstName, SecondName, LastName, Faculty, 
    Specialty, OKS, StudentStatus, FakNumber, Course, Potok, [[Group]]]) 
    VALUES (@fName , @sName, @lName, @faculty, @specialty, @OKS, 
    @StudentStat, @fak, @Course, @Porok, @Group) 
    RETURN 2; 

當我通過DatabaseExplorer測試程序(VS2013)一切正常,並記錄插入進入桌子。但是當我在c#中調用過程時,什麼都不會發生。貝婁是我用來調用的程序方法的代碼:

public static bool InsertStudent (Student student) 
    { 
     StudentDataClassesDataContext dc = new StudentDataClassesDataContext(); 
     try 
     { 
      int returnValue = dc.AddNewStudent(student.FirstName, student.SecondName, student.LastName, student.Faculty, student.Specialty, student.OKS, student.StudentStatus, 
       student.FakNumber, student.Course, student.Potok, student._Group_); 
      dc.SubmitChanges(); 
      MessageBox.Show("Return Value : " + returnValue, "Info", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show("Exception : " + e.Message, "Info", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
      return false; 
     } 
     return true; 
    } 

返回的值是2,這意味着程序做它的工作,但爲什麼沒有插入到表中的記錄?我讀了使用dc.SubmitChanges()而不是Commit。

+0

您是否看到帶有「返回值:2」的消息框? –

+0

你正在使用什麼**連接字符串**? –

+0

您是否在您的存儲過程結束時提交? – Ramie

回答

-1

一切都沒問題的代碼。這個問題與數據庫和項目本身之間的聯繫有關。

0

您可以啓動Sqlserver Profiler來查看會發生什麼,查看是否有沒有提交的事務啓動? 您也可以只dc.submitchanges後設置一個斷點(),當你的應用程序命中破發點,去到SQL Server並運行此查詢

Select * from [Students] with (nolock) 

,並確保數據在你的桌子,後繼續運行你的應用程序並再次運行該查詢,如果數據在你的表中,並且沒有消失,那麼存在未定義的事務。解決這個問題只需使用TransactionScope。如果數據從一開始就不在您的表中,您可能會在另一個數據庫上運行您的代碼。您可以在datacontext構造函數中傳遞connnctionstring。

+0

嗨RezaRahmati,謝謝你的回答。 我確實在dc.submitchanges()之後設置了一個斷點,並且檢查了數據庫但沒有插入記錄。 我試着用另一種方法,但結果是一樣的 - 沒有記錄被插入。但是,當從數據庫中選擇查詢時,它會返回信息。它可能是特權有問題嗎?波紋管是我使用的新方法。正如你所看到的,我用TransactionScope嘗試過,但沒有任何改變 – user3459077

+0

http://dox.bg/files/dw?a=a433c86d82 - 這裏是方法 – user3459077

+0

只是爲了確定你在查詢後設置了(nolock)' 'cmd.ExecuteNonQuery()'因爲你的數據在事務中,數據不會顯示直到提交事務,除非你使用'with(nolock)' – RezaRahmati