我正在尝试检查是否有一行插入到我的数据库中。即使它插入时也会抛出错误(这是一个数据库问题,以后我得到更新版本的Microsoft Access时会解决),所以我无法根据是否有错误来检查插入是否成功。我想我需要查看AffectedRows的某些内容,但我不确定是什么。我一直在寻找有关如何做到这一点的信息,但我无法弄清楚如何让它适合我的确切情况。以下是我的代码的基本概念:
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()
-UPDATE -
我试过这样:
'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
但是,即使插入成功,numInserted也会每次出现0。它可能与myIns1.ExecuteNonQuery()即使插入成功也会抛出错误这一事实有关。
-EDIT-我发现“重复值”错误是因为它以某种方式试图插入记录两次。我不知道为什么会这样做。
答案 0 :(得分:0)
ExecuteNonQuery函数返回受影响的行数...
Dim numInserted as Integer = myIns1.ExecuteNonQuery()
If numInserted = 0 Then
' no rows were inserted...throw exception?
End If
答案 1 :(得分:0)
您所描述的症状(已知没有重复,但插入丢失重复的错误)听起来像您的Access数据库需要Compacting and Repairing。
你应该定期这样做。 (始终先备份)。