I am trying to check whether a row is getting inserted into my database. It is throwing an error even when it does insert (it's a database issue that will get resolved later when I get a newer version of Microsoft Access), so I can't check whether the insert is successful based on whether there's an error or not. I think I need to check the AffectedRows of something, but I'm not sure what. I've been looking for info on how to do this but I can't figure out how to make it work for my exact situation. Here's a general idea of what my code looks like:
Protected Sub Wizard1_FinishButtonClick(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles Wizard1.FinishButtonClick
'code for collecting data...
'Define Connection
Dim myConn As New OleDbConnection
myConn.ConnectionString = AccessDataSource1.ConnectionString
myConn.Open()
'Insert command
Dim myIns1 As New OleDbCommand("INSERT INTO tableCourse 'long insert command here...
'Execute command and handle errors
Try
myIns1.ExecuteNonQuery()
Catch myException5 As Exception
End Try
'Close connection
myConn.Close()
开发者_如何学Go
-UPDATE-
I tried it like this:
'Execute command, handle errors, and check if row was inserted
Dim numInserted As Integer = 0
Try
numInserted = myIns1.ExecuteNonQuery()
Catch myException As Exception
Finally
If numInserted = 0 Then
Label1.Text = "Sorry, an error occured."
Else
Label1.Text = "Thank you! Your new course approval request has been submitted."
End If
End Try
But the numInserted is coming out as 0 every time even though the insert is successful. It may have to do with the fact that myIns1.ExecuteNonQuery() throws an error even though the insert is successful.
-EDIT- I discovered that the "duplicate values" error is because it is somehow attempting to insert the record twice. I have no idea why it's doing that though.
The ExecuteNonQuery function returns the affected number of rows...
Dim numInserted as Integer = myIns1.ExecuteNonQuery()
If numInserted = 0 Then
' no rows were inserted...throw exception?
End If
The symptoms you are describing (known no duplicates, but inserts throw duplicate errors) sound like your Access database needs Compacting and Repairing.
You should do this on a regular basis. (Always backup up first).
精彩评论