寻求帮助,如果记录不在数据库中或数据库中没有数据,我如何推入msgbox错误。即时通讯使用vb.net和sql检查记录。不确定怎么办,
这是我的代码
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
While dr.Read()
'Main.BGCPnl.Visible = True
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
//>Here is my code for the error message when record is not
found, im not sure what will be the right code.
i used count parameter
BGCEmp = dr(ADS.UserEmpID)
If BGCEmp.Count = 0 Then
MsgBox("no record")
Exit Sub
End If
End While
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
答案 0 :(得分:1)
您应该学习如何正确使用数据读取器的Read
方法和HasRows
属性。如果永远不会有一个以上的记录,但可能没有一个,则仅使用Read
:
If myDataReader.Read() Then
'There is a row and you can access its data here.
Else
'There are no rows.
End If
如果可能有多行,或者没有行或者在没有行的情况下您不需要做任何特定的事情,那么只需使用Read
:
While myDataReader.Read()
'Access the current row here.
End While
如果没有行,那么您就永远不会进入循环,执行之后就继续执行。
如果可能存在零行,一行或多行,并且在没有行的情况下确实需要做一些特定的事情,请同时使用HasRows
和Read
:
If myDataReader.HasRows Then
'There is at least one row so read the data.
While myDataReader.Read()
'Access the current row here.
End While
Else
'There are no rows.
End If
在某些情况下,您只在乎是否有数据,而无需数据本身。在这种情况下,只需使用HasRows
:
If myDataReader.HasRows Then
'There is a at least one row
Else
'There are no rows.
End If
在这种情况下,我建议您应该执行类似在查询中使用COUNT
函数并调用ExecuteScalar
而不是调用ExecuteReader
的事情。
答案 1 :(得分:0)
Try
myConnection.Open()
str = "SELECT * FROM tblEmp WHERE (EmpID = '" & ADS.UserEmpID & "')"
Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
dr = cmd.ExecuteReader
If dr.HasRows Then
While dr.Read()
BGC1 = dr("PreStartChecks").ToString
BGC2 = dr("EmpName").ToString
End While
Else
MessageBox.Show("No Record found", "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error)
Exit Sub
End If
Catch ex As Exception
MsgBox("Unable to Connect to BGC DB. You may not have access or DB not available." & ex.ToString)
End Try
myConnection.Close()
阅读有关Read()
和HasRows
的文档。