0

当我运行这个功能

    For RepeatBooking = 1 To 51
        dateConvertedDateToBook = dateDateToBook.Date
        dateDateToBook = dateDateToBook.AddDays(7)
        strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")

        Try
            Dim command As MySqlCommand = New MySqlCommand
            Dim sqlQuery As String = "INSERT INTO bookings SET Date=" & "'" & strDateToBook & "',RoomID='" & strComputerRoomToBook & "',Length='" & intNewBookingLength & "',Period='" & intNewStartPeriod & "',UserID='" & intid & "'"
            Dim reader As MySqlDataReader
            SQLConnection.Open()
            command.CommandText = sqlQuery
            command.Connection = SQLConnection
            reader = command.ExecuteReader
            SQLConnection.Close()
        Catch excep As Exception
            MsgBox(excep.ToString)
        End Try

    Next

在我的程序中,我收到一条错误消息“连接属性尚未设置或为空”我该如何摆脱这个?

当它到达 SQLconnection.Open() 时出现异常 我在模块顶部创建了 ServerString 和 MySQL 连接,如下所示:

Dim ServerString As String = "Server=localhost;User Id=root;Password=**********;Database=rooms"
Dim SQLConnection As MySqlConnection = New MySqlConnection
4

1 回答 1

0

您正在打开一个没有其属性的连接
它应该是,

Dim SQLConnection As New MySqlConnection(ServerString)
SQLConnection.Open  

此外,您可能希望使用该USING功能以正确关闭连接。
您似乎只是在数据库中插入了一堆值,而没有检索任何内容,那么为什么要使用 DataReader?
你的代码应该是这样的:

Using SQLConnection = New MySqlConnection(ServerString)  
    SQLConnection.Open  'You should open a connection only once
    For RepeatBooking = 1 To 51
        dateConvertedDateToBook = dateDateToBook.Date
        dateDateToBook = dateDateToBook.AddDays(7)
        strDateToBook = dateConvertedDateToBook.ToString("yyyy-MM-dd")
        Try
            Dim sqlQuery As String = "INSERT INTO bookings SET " & _ 
                "Date='" & strDateToBook & "'," & _
                "RoomID='" & strComputerRoomToBook & "', " & _
                "Length='" & intNewBookingLength & "', " & _
                "Period='" & intNewStartPeriod & "', " & _
                "UserID='" & intid & "'"
            Dim command = New MySqlCommand(sqlQuery, SQLConnection)
            command.ExecuteNonQuery
        Catch excep As Exception
            MsgBox(excep.Message)
        End Try  
     Next  
End Using

此外,您可能希望更改将值传递给参数的方式。这将防止 SQL 注入。

于 2013-02-21T16:56:12.357 回答