Dim ColNames(7) As String
Dim Values(7) As Object
Dim now As DateTime = DateTime.Now()
ColNames(0) = "Int1"
ColNames(1) = "Int2"
ColNames(2) = "String1"
ColNames(3) = "String2"
ColNames(4) = "String3"
ColNames(5) = "String4"
ColNames(6) = "String5"
ColNames(7) = "String6"
Values(0) = intVar1
Values(1) = intVar2
Values(2) = strVar1
Values(3) = strVar2
Values(4) = strVar3
Values(5) = strVar4
Values(6) = strVar5
Values(7) = strVar6
Dim goodToInsert As Boolean = True
For i As Integer = 0 To 7
If Values(i) = Nothing OrElse Len(Values(i)) = 0 Then
goodToInsert = False
End If
Next
If goodToInsert Then
accessDatabase.InsertIntoTable("MyTable", ColNames, Values)
End If
这部分代码处理收集数据以插入我的访问数据库。
Public Sub InsertIntoTable(ByRef TableName As String, ByRef ColumnName() As String, ByRef KeyValue() As Object)
'ColumnName and KeyValue need to have the same number of elements
'be careful when attemping to insert a value into the PrimaryKey Column as it may be of a type that cannot but manually changed
'INSERT NEW DATA INTO A TABLE
' INSERT INTO {tablename} ([{columnname1}], [{columnname2}], [{columnname3}], ...) VALUES ('{string}', {number}, {boolean}, ...), oledbconnection
Dim ColumnString As String = vbNullString
Dim KeyString As String = vbNullString
For i As Integer = 0 To ColumnName.GetUpperBound(0)
'build the column names part of the string
If i <> ColumnName.GetUpperBound(0) Then
ColumnString = ColumnString & "[" & ColumnName(i) & "], "
Else
ColumnString = ColumnString & "[" & ColumnName(i) & "]"
End If
'build the values part of the string
Dim TempValue As String = vbNullString
If KeyValue(i) <> Nothing Then
If KeyValue(i).GetType.ToString = "System.String" Then
TempValue = "'" & KeyValue(i) & "'"
Else
TempValue = KeyValue(i)
End If
If i <> KeyValue.GetUpperBound(0) Then
KeyString = KeyString & vbNullString & TempValue & ", "
Else
KeyString &= TempValue
End If
Else
Debug.Print("Nothing")
If i <> KeyValue.GetUpperBound(0) Then
KeyString &= ", "
End If
End If
Next
Dim con As New OleDbConnection
Dim da As New OleDbDataAdapter
Dim sql As New OleDbCommand
con.ConnectionString = Connection()
con.Open()
Dim commandText As String = "INSERT INTO " & TableName & " (" & ColumnString & ") VALUES (" & KeyString & ")"
Try
sql.Connection = con
sql.CommandText = commandText
da.InsertCommand = sql
da.InsertCommand.ExecuteNonQuery()
Catch ex As Exception
Debug.Print(ex.ToString)
End Try
con.Close()
End Sub
这是 InsertIntoTable 函数。
该函数正常运行并将数据正确插入我的表中,但在我的调试输出中,我在每次调用 da.InsertCommand.ExecuteNonQuery() 时都会注意到此错误:
First-chance exception at 0x761EC42D in 3024 Card Sorter.exe: Microsoft C++ exception: int at memory location 0x003ED1EC.
First-chance exception at 0x761EC42D in 3024 Card Sorter.exe: Microsoft C++ exception: int at memory location 0x003ED1EC.
我能够使用 Visual Studio 调试器将其缩小到 ExecuteNonQuery() 发生的位置,但我无法理解它的含义以及如何解决它。我尝试将我的 intVars 更改为字符串,但没有解决异常,我也非常好奇为什么我的 Try...Catch 没有捕获到它。