在VB中从MySQL数据库中检索多个条目

时间:2013-02-17 23:53:50

标签: mysql database arrays vb.net

我正在为我的学校计算课程建立一个房间预订服务,我不完全确定如何从数据库中检索以前制作的预订。我知道如何连接到数据库并读取一个条目但不是多个条目。

到目前为止,我有:

   strBookingQuery = "SELECT * FROM bookings WHERE Date = '" & ConvertedBookingDate & "'"

    Dim Cmd As New MySqlCommand(strBookingQuery, Newconnection)
    Newconnection.ConnectionString = strServerString
    Newconnection.Open()
    reader = Cmd.ExecuteReader()
    reader.Read()

这从数据库中提取了5个变量,日期,预订的时间,预订的长度,UserID和RoomID的顺序,我希望将它们写成整数,将最后四个变量转换为整数数组,数组大小为7,因为一天中的最大预订数为7.任何帮助将不胜感激:)

我也为任何糟糕的编码道歉,我是一名A级学生,所以我很长时间没有编码。

有什么想法吗?

Function GetBookingData()

    strBookingQuery = "SELECT * FROM bookings WHERE Date = '" & ConvertedBookingDate & "'"

    Dim Cmd As New MySqlCommand(strBookingQuery, Newconnection)
    Newconnection.ConnectionString = strServerString
    Newconnection.Open()
    reader = Cmd.ExecuteReader()
    reader.Read()
    For SP = 1 To intBookingCount
        Do While reader.Read()
            StartPeriod(SP) = reader.GetInt16(1)
        Loop
        MsgBox(StartPeriod(SP))
    Next

    Newconnection.Close()

End Function

1 个答案:

答案 0 :(得分:0)

目前还不完全清楚你的尝试是什么,但我怀疑你真正想要的是这样的:

Function GetBookingData()
    strBookingQuery = "SELECT * FROM bookings WHERE Date = '" & ConvertedBookingDate & "'"
    Dim Cmd As New MySqlCommand(strBookingQuery, Newconnection)
    Newconnection.ConnectionString = strServerString
    Newconnection.Open()
    reader = Cmd.ExecuteReader()
    For SP = 1 To intBookingCount
        If Not reader.Read() Then
            Exit For
        End If
        StartPeriod(SP) = reader.GetInt16(1)
        MsgBox(StartPeriod(SP))
    Next
    Newconnection.Close()    
End Function

但是,我会提出一些进一步的建议。首先,如果可能,您应为您使用的每个Using对象添加IDisposable块(例如Newconnection,Cmd)。 Using块更安全,因为如果执行因任何原因(例如异常)而离开块,它仍将为您正确处理该对象。

其次,您应该在命令中使用参数,而不是将日期值直接附加到strBookingQuery字符串中。当您自己将值附加到SQL字符串中时,您将数据库打开为SQL注入攻击。此外,特别是日期,你也可能遇到文化差异(例如MM-dd-yyyy与dd-MM-yyyy)。

第三,使用某种集合(例如List(Of Integer))来存储从数据库读取的值而不是数组中会更容易。假设行数总是相同的固定大小并不好,并且在处理可变长度列表时使用数组是不方便的。收藏品正是为了那种东西而精心制作的。使用集合而不是跟踪数组中的固定长度和当前索引,您只需在需要添加新项目时调用Add方法。

所以,我的建议是更像这样:

Public Function GetBookingData(bookingDate As Date) As List(Of Integer)
    Dim data As New List(Of Integer)()
    Using connection As New MySqlConnection()
        connection.ConnectionString = connectionString
        connection.Open()
        Dim query As String = "SELECT * FROM bookings WHERE Date = @BookingDate"
        Using command As New MySqlCommand(query, connection)
            Dim parameter As IDbDataParameter = command.CreateParameter()
            parameter.ParameterName = "@BookingDate"
            parameter.Value = bookingDate
            command.Parameters.Add(parameter)                
            Using reader As DbDataReader = cmd.ExecuteReader()
                Do While reader.Read()
                    data.Add(reader.GetInt16(1))
                Loop
            End Using
        End Using
    End Using
    Return data
End Function