我正在尝试检查访问数据库中的空记录,并认为我使用的代码可以正常工作。应该发生的是,如果db中没有该表的记录,则显示msgbox。但是,运行代码时没有显示任何内容。我使用IsDBNull是正确的方法还是有更好的方法来做到这一点。我正在努力使用params代替&参考,这将在测试后更改。非常感谢。
Dim con1 As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\domain\test.accdb")
Dim sql As String
sql = "SELECT * FROM Departments where Customer = '" & customer & "'"
If IsDBNull(sql) Then
MessageBox.Show("No record") <---THIS NOT FIRING
' This is our DataAdapter. This executes our SQL Statement above against the Database
' we defined in the Connection String
Else
Dim adapter As New OleDbDataAdapter(sql, con1)
' Gets the records from the table and fills our adapter with those.
Dim dt As New DataTable("Departments")
adapter.Fill(dt)
' Assigns our DataSource on the DataGridView
dgv1.DataSource = dt
'
Dim sql1 As String
sql1 = "SELECT * FROM Departments"
Dim adapter1 As New OleDbDataAdapter(sql1, con1)
Dim cmd1 As New OleDbCommand(sql1, con1)
'Dim dt1 As New DataTable("Departments")
con1.Open()
Dim myreader As OleDbDataReader = cmd1.ExecuteReader
myreader.Read()
con1.Close()
End If
答案 0 :(得分:2)
是的,您使用IsDBNull
完全错误。该方法的文档说明:
返回一个布尔值,指示表达式是否计算为System.DBNull类。
您发送到sql
方法的IsDBNull
变量显然不会评估为System.DBNull
,因为您自己将其设置为其他值。
执行SQL后使用IsDBNull
,检查结果中的特定字段是否为NULL。要做你想做的事,你只需要在调用Fill
后检查数据表中是否有任何行。
Dim dt As New DataTable("Departments")
adapter.Fill(dt)
If dt.Rows.Count = 0 Then MessageBox.Show("No record")
答案 1 :(得分:1)
IsDbNull不会调用您的数据库。它只是测试参数是否等于DbNull.Value,如果用字符串调用它将永远不会出现这种情况。
你可以试试这个
Dim con1 As New OleDbConnection("Provider = Microsoft.ACE.OLEDB.12.0;Data Source=C:\domain\test.accdb")
Dim sql As String
sql = "SELECT COUNT(*) FROM Departments where Customer = '" & customer & "'"
con1.Open()
Dim cmd1 As New OleDbCommand(sql, con1)
If cmd1.ExecuteScalar() = 0 Then
MessageBox.Show("No record")
Else
Dim adapter As New OleDbDataAdapter(sql, con1)
' Gets the records from the table and fills our adapter with those.
Dim dt As New DataTable("Departments")
adapter.Fill(dt)
' Assigns our DataSource on the DataGridView
dgv1.DataSource = dt
'
Dim sql1 As String
sql1 = "SELECT * FROM Departments"
Dim adapter1 As New OleDbDataAdapter(sql1, con1)
cmd1 = New OleDbCommand(sql1, con1)
'Dim dt1 As New DataTable("Departments")
Dim myreader As OleDbDataReader = cmd1.ExecuteReader
myreader.Read()
con1.Close()
End If