我希望datareader从数据库中的列读取数据,该列是varchar,读取结果存储在字符串变量中

时间:2011-08-16 12:12:22

标签: sqldatareader datareader

我希望datareader从数据库中的列读取数据,该数据是varchar,读取结果存储在字符串变量中,但它会生成indexoutofrange异常...基本上我想要验证,以便用户输入预订时间已经在数据库中的程序应该生成错误消息。如果输入的值在预订的持续时间内,则还应生成错误。如果在12/12/2011下午4:00预订,并且持续时间为2小时,则该计划不应允许任何预订,直到下午6:00,除非预订用于其他游戏或其他一些courtno(如羽毛球,壁球,草地网球等)

我正在尝试以下代码:

Dim str2 As String'定义用于获取选择查询的字符串变量

    str2 = "select booking_date, booking_time, booking_duration, poolno, courtno, tableno from Bookings"

    Dim a, b As Date
    Dim c As Date
    Dim d, f, g, l As String

    Dim dur As Integer

    Dim cmd2 As New SqlCommand(str2, con)
    con.Open()

    Dim bookchk As SqlDataReader = cmd2.ExecuteReader
    While bookchk.Read()
        a = bookchk("booking_date")
        b = bookchk("booking_time")
        c = b.ToLongTimeString
        dur = bookchk("booking_duration")

        l = bookchk("game") 'exception is generated here


        If CmboGame.SelectedItem = "Swimming" Then
            If bookchk("poolno") IsNot System.DBNull.Value Then
                d = bookchk("poolno")

            End If

        Else : d = ""

        End If

        If CmboGame.SelectedItem = "Table Tennis" Then
            If bookchk("tableno") IsNot System.DBNull.Value Then
                f = bookchk("tableno")

            End If
        Else : f = ""
        End If
        If CmboGame.SelectedItem IsNot "Table Tennis" And CmboGame.SelectedItem IsNot "Swimming" Then
            If bookchk("courtno") IsNot System.DBNull.Value Then
                g = bookchk("courtno")

            End If
        Else : g = ""
        End If
        If TxtBookDate.Text = a And TxtBookTime.Text = c And TxtPoolNo.Text = d And TxtCrtNo.Text = g And TxtTblNo.Text = f And CmboGame.SelectedItem = l Then
            MessageBox.Show("The date and time you have entered has already been booked" & vbCrLf & "Try Again!", "Bookings Overlapped", MessageBoxButtons.OK, MessageBoxIcon.Stop)
            Exit Sub

        End If


        Dim time, h, i, j, n As DateTime
        n = c.AddHours(dur)
        time = TxtBookTime.Text
        h = time.AddHours(TxtBookDur.Text)
        i = time.ToLongTimeString
        j = h.ToLongTimeString


        If TxtBookDate.Text = a And TxtPoolNo.Text = d And TxtCrtNo.Text = g And TxtTblNo.Text = f And CmboGame.SelectedIndex = l And i > c And i <= n Or j > n Then
            MessageBox.Show("The date and time you have entered has already been booked" & vbCrLf & "Try Again!", "Bookings Overlapped", MessageBoxButtons.OK, MessageBoxIcon.Stop)

            Exit Sub

        End If


    End While
    bookchk.Close()
    con.Close()

1 个答案:

答案 0 :(得分:0)

您的SQL语句:

str2 = "select booking_date, booking_time, booking_duration, poolno, courtno, tableno from Bookings"

您没有选择名为“游戏”的列,因此很明显您无法在datareader中引用它。将“游戏”列添加到SQL语句中,假设它存在,此问题将消失。当然,你可能还有其他问题。