【问题标题】:Why can't vb catch a query error为什么 vb 不能捕获查询错误
【发布时间】:2014-02-04 09:03:20
【问题描述】:

这是我当前的代码:

Dim query As String = "SELECT * FROM tblPiglets WHERE Week=@week AND SowOrder=@so AND PigletNumber=@pig"

    Using cmd As New OleDbCommand(query, con)
        With cmd.Parameters
            .AddWithValue("@week", txtWeek.Text)
            .AddWithValue("@so", txtSo.Text)
            .AddWithValue("@pig", txtPiglet.Text)
        End With
        Dim dr As OleDbDataReader = cmd.ExecuteReader()
        While dr.Read
            Dim loc As String
            loc = dr("CurrentLocation").ToString()
            If loc = ComboBox1.Text Then
                confirmed()
            Else
                invalid()
            End If
        End While
    End Using

第一个用户必须输入一个唯一的 id,即周、母猪顺序和编号。然后它将检查所选项目的CurrentLocation 字段是否与ComboBox1.Text 相同。如果是,继续,如果不是,错误。
但是,当用户插入不存在数据时,什么都不会发生。比如说,我有 3 个数据(唯一的“id”)。

  1. 1-1-0
  2. 1-1-1
  3. 2-1-0

如果我尝试输入 2-1-1,不存在,什么也没有发生。我想抓住这个,所以用户会知道这是一个无效的输入。

【问题讨论】:

    标签: .net vb.net ms-access


    【解决方案1】:

    您需要自己检查是否有任何结果。对于 SQL 查询,如果它不返回任何行,则不是错误。
    以下代码是此类检查的示例:

    Dim dr As OleDbDataReader = cmd.ExecuteReader()
    If dr.Read() Then
        Do 
           Dim loc As String
           loc = dr("CurrentLocation").ToString()
           If loc = ComboBox1.Text Then
               confirmed()
           Else
                invalid()
            End If
       Loop While dr.Read()
    Else
        ' Add code for no records here
    End If
    

    请注意,如果您想专门检查无效 id,则需要为此添加特殊检查。上面的示例仅检查是否返回了任何行。造成这种情况的原因也可能是没有一周或 soworder 的数据。

    【讨论】:

    • 这很好,我只是想根据用户输入来捕捉是否不存在数据。谢谢
    【解决方案2】:

    添加一些检查 dr 不为空的代码。

    If Not IsNothing(dr) Then
       While dr.read.... 
    
    Else
      'No records
    End If
    

    【讨论】:

      猜你喜欢
      • 2018-11-21
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-30
      • 2021-06-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多