我有一个需要整数的字段的访问数据库。我正在传递从 Excel 电子表格中检索到的一些数据,如果从单元格中检索到字符串,则调用函数的 Try/Catch 将遇到 FormatException。我想弄清楚的是是否有可能(并且总是)抛出一个自定义错误消息,该消息将显示包含无效数据的单元格地址。这是我所拥有的一些示例代码。
Public Class Main
Private cellAddress As String
Private Sub btn_Import(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImport.Click
Dim openFileDialog As New OpenFileDialog()
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
openFileDialog.Filter = "Excel Files (*.xls)|*.xlsx|All files (*.*)|*.*"
openFileDialog.RestoreDirectory = True
If openFileDialog.ShowDialog() <> Windows.Forms.DialogResult.OK Then
Return
End If
Try
ImportWorksheet(New FileInfo(openFileDialog.FileName))
Catch ex As FormatException
MessageBox.Show("The data contained within cell " & cellAddress & " is invalid.", "Error")
End Try
End Sub
Private Sub ImportWorksheet(ByVal excelFile As FileInfo)
Dim cnn As New OleDbConnection(My.Settings.cnn)
Dim cmd As OleDbCommand = GetCommand("UpdateSite")
Dim worksheet1 As ExcelWorksheet = package.Workbook.Worksheets(1)
Using package As New ExcelPackage(excelFile)
Using cmd.Connection
cmd.Connection.Open()
cmd.Parameters.Add("@MyData", OleDbType.Integer).Value = GetCellContents(worksheet1, "K8")
cmd.ExecuteNonQuery()
End Using
End Sub
Private Function GetCellContents(ByVal worksheet As ExcelWorksheet, ByVal address As String) As Object
If worksheet.Cells(address).Value Is Nothing Then
Return DBNull.Value
Else
cellAddress = address
Return worksheet.Cells(address).Value
End If
End Function
End Class
不要认为我在这里遗漏了任何东西,我复制并粘贴并更改了代码以缩短并且不放弃任何不需要的信息。一旦代码到达 ExecuteNonQuery() 方法,错误就会冒出并说出我写的任何内容。如果可能的话,我想在发生这种情况时传递单元格地址,以便他们知道在哪里查找。
我能想到的唯一方法是添加一个类级别变量,并在每次获取值时将其设置为当前单元格。唯一的问题是,因为它只在 ExecuteNonQuery() 触发,并且我有多个参数,如果第一个添加的参数无效但下一个参数不是,那么每次将单元格设置为最后一个参数,我得到错误的结果。有没有办法从数据库中获取某种消息,具体告诉我哪个参数没有正确转换?