如何处理此类错误或异常?
Try
If log.Trim = txtUSN.Text Then
MessageBox.Show("USN found: " & log)
Else
MessageBox.Show("USN not found: " & log)
End If
Catch ex as Exception
MessageBox.Show(ex.Message)
消息是"对象引用未设置为对象的实例。"
这是代码的其余部分:
Dim log As String
Dim sql As New SqlCommand
sql.Connection = MyConnection
sql.CommandText = "SELECT * FROM dbo.tblAcc WHERE USN = '" & txtUSN.Text & "' "
MyConnection.Open()
log = sql.ExecuteScalar
MyConnection.Close()
答案 0 :(得分:0)
简单的答案是 您尝试使用的对象 。如果没有,你就无法使用它,因此“对象引用未设置为对象的实例”。
正如我在上面的评论中已经提到的,罪魁祸首是:log
。我不确定你在哪里声明这个或者你使用它以及你如何使用它,因为我知道它什么都没有。如果你有更多的代码值得高度赞赏,因为我可以指出什么都没有,直到那时这里是如何解决你的问题。
Try
If log IsNot Nothing Then
If log.Trim = txtUSN.Text Then
MessageBox.Show("USN found: " & log)
Else
MessageBox.Show("USN not found: " & log)
End If
Else
MessageBox.Show("Log is NOTHING!")
End If
Catch ex as Exception
MessageBox.Show(ex.Message)
End Try
<强> **编辑** 强>
在评论中发布更多代码后(请在该区域发布代码,而不是评论中的代码),似乎有一些问题。您将log
定义为字符串;当你这样做时,将它设置为:String.Empty
而不是什么。您还希望使用ExecuteScalar方法从数据库中检索单个值(例如,聚合值),该数据库可以是整数,长整数,单个等数据类型。在您的查询中选择所有内容,您无法调用ExecuteScalar来返回该数据...我建议您查找有关构建查询和执行查询的信息,这是我在这里深入了解它。
快乐的编码!
答案 1 :(得分:0)
确保(日志)不是空字符串。
if not String.IsNullorEmpty(log) then
end if