2016-08-02 62 views
0

我的代碼中有以下子例程,用於將新記錄插入到SQL Server數據庫中。在逐步完成代碼後,代碼完成所有操作,出現消息框,但該行實際上並未插入到數據庫中。我知道它使用正確的連接,因爲我可以在使用SQL Server手動插入的相關網格上查看記錄,而且我的UPDATEDELETE查詢也可以使用相同的連接,所以我的代碼有些問題,但我無法弄清楚什麼......任何人都可以幫助我嗎?INSERT查詢正在執行但未插入

Public Shared Function SaveNewIncident(ByVal clientName As String, dateStart As Date, dateEnd As Date, ByVal incidentProblem As String, ByVal timeStart As String, ByVal timeEnd As String, 
             ByVal incidentSolved As Boolean, ByVal incidentSolution As String, _con As OleDbConnection) 

    Dim tr As OleDbTransaction = Nothing 

    Try 
     tr = _Con.BeginTransaction() 

     Dim Dc As New OleDbCommand 
     Dc.Connection = _con 

     Dim ID As Integer 
     ID = "1" 

     Dc.CommandType = CommandType.Text 
     Dc.CommandText = "INSERT INTO dbo.tblIncidents VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)" 
     Dc.Transaction = tr 
     Dc.Parameters.Add("@supportID", OleDbType.Integer).Value = ID 
     Dc.Parameters.Add("@clientName", OleDbType.VarChar).Value = clientName 
     Dc.Parameters.Add("@dateStart", OleDbType.Date).Value = dateStart 
     Dc.Parameters.Add("@dateEnd", OleDbType.Date).Value = dateEnd 
     Dc.Parameters.Add("@incidentProblem", OleDbType.LongVarChar).Value = incidentProblem 
     Dc.Parameters.Add("@timeStart", OleDbType.VarChar).Value = timeStart 
     Dc.Parameters.Add("@timeEnd", OleDbType.VarChar).Value = timeEnd 
     Dc.Parameters.Add("@incidentSolved", OleDbType.Boolean).Value = incidentSolved 
     Dc.Parameters.Add("@incidentSolution", OleDbType.LongVarChar).Value = incidentSolution 

     tr.Commit() 

     MsgBox("Save successful") 

    Catch ex As Exception 

     mdInit.errorLog(ex.Message, ex.StackTrace) 
     MsgBox("Failed to save data, refer to error log") 
     tr.Rollback() 

    End Try 

End Function 
+4

我覺得你需要之前'tr.Commit調用'Dc.ExecuteNonQuery()'()' – user5226582

+0

@ user5226582是的,謝謝你,當然...只是一些愚蠢的 – David

回答

2

您還沒有執行插入查詢。添加下面的代碼之前tr.Commit()

Dc.ExecuteNonQuery() 
+0

謝謝Akshey,這工作。我想改變的一件事是,在這段代碼中,supportID始終輸入爲1 ...我如何調整代碼以找到數據庫中最高的ID號,添加1並插入此數字? – David

+1

將support-id列轉換爲標識列。這樣你將永遠得到所需的價值。 –

+0

我原來是這樣的,但是在程序中有一點我需要它,因爲當你想要插入明確的值到標識列時,我必須插入明確的值 – David