我正在尝试从ACCESS数据库中提取数据。
实际上,代码有效,并且没有错误...... 但是,如果记录不存在,我似乎无法显示消息框。它只返回一个空字符串。
Using dbCon = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source = '" & Application.StartupPath & "\Res\T500G.accdb'")
dbCon.Open()
Dim Query1 As String = "SELECT SUM(Total) FROM [T500] WHERE Pro=@Pro"
Dim cmd1 As OleDb.OleDbCommand = New OleDbCommand(Query1, dbCon)
cmd1.Parameters.AddWithValue("@Pro", ComboBoxBP.SelectedItem.ToString)
Dim reader As OleDb.OleDbDataReader
reader = cmd1.ExecuteReader
While reader.Read()
TextBox1.Text = reader.GetValue(0).ToString
End While
reader.Close()
dbCon.Close()
End Using
我尝试在文本框中使用If reader.hasrows then
显示结果,否则显示消息框等,但它不起作用。
If reader.HasRows Then
While reader.Read()
TextBox1.Text = reader.GetValue(0).ToString
End While
Else
MessageBox.Show("asd")
End If
如果我从.ToString
删除了reader.GetValue(0)
,如果数据库中不存在组合框中的所选项目,则会收到错误消息。无法将DBNull转换为整数或其他内容。
所以我的问题是,如果记录“@Pro”不存在,如何显示消息框?
感谢〜
使用此
修复(解决方法)Dim ValueReturned As String
While reader.Read()
ValueReturned = reader.GetValue(0).ToString
If ValueReturned = "" Then
MessageBox.Show("Not Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
MetroTextBox1.Text = ValueReturned
End If
End While
答案 0 :(得分:1)
您可以将查询更改为(这适用于SQL-Server):
IF EXISTS (SELECT * FROM [T500] WHERE Pro = @Pro) SELECT SUM(Total) FROM [T500] WHERE Pro = @Pro ELSE SELECT 'Not Found'
并将您的代码更改为:
Dim ValueReturned As String
While reader.Read()
ValueReturned = reader.GetValue(0).ToString
End While
If ValueReturned Is Nothing OrElse ValueReturned = "Not Found" Then
MessageBox.Show("Not Found", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
TextBox1.Text = ValueReturned
End If
答案 1 :(得分:1)
使用OleDbDataReader
对于您的查询来说不是最理想的,因为它永远不会返回一组要遍历的记录:
Dim sql = "SELECT SUM(...=@p1"
' rather than sprinkling you connection string all over
' the app, you can make a function returning one
Using conn As OleDbConnection = GetConnection(),
cmd As New OleDbCommand(sql, GetConnection())
conn.Open())
' ToDo: Check that ComboBoxBP.SelectedItems.Count >0 before this
cmd.Parameters.AddWithValue("@p1", ComboBoxBP.SelectedItem.ToString)
' execute the query, get a result
Dim total = cmd.ExecuteScalar
' if there is no matches, OleDb returns DBNull
If total Is System.DBNull.Value Then
' no matches
MessageBox.Show("No matching records!"...)
Else
MessageBox.Show("The Total is: " & total.ToString()...)
End If
End Using ' disposes of the Connection and Command objects
另外,您可以使用If IsDBNull(total) Then...
。如果你愿意,你也可以转换它:
Dim total = cmd.ExecuteScalar.ToString()
' DBNull will convert to an empty string
If String.IsNullOrEmpty(total) Then
MessageBox.Show("No Soup For You!")
Else
...
End If