使用代码更新时,“在System.Data.dll中出现'类型'System.Data.OleDb.OleDbException'的第一次机会异常”

时间:2018-01-04 12:11:34

标签: sql vb.net ms-access updating

我的OCCUPIED - 列为Boolean,我希望更改房间​​状态,以便它不会显示在免费房间列表中。

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
    dataFile = "C:\Users\MAI KUDA\Documents\Visual Studio 2008\Projects\HOTEL MANAGMENT\HOTEL MANAGMENT\bin\Debug\MY HOTEL.accdb"
    connString = provider & dataFile
    myConnection.ConnectionString = connString
    myConnection.Open()
    Dim str As String
    str = "update [ROOMS] set [OCCUPIED]=?status, [occupied by]=?name Where [ROOM] = ?room  "
    Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
    cmd.Parameters.AddWithValue("?status", True)
    cmd.Parameters.AddWithValue("?name", Form3.NAMETextBox.Text And Form3.SURNAMETextBox.Text)
    cmd.Parameters.AddWithValue("?room", ROOMTextBox.Text)

    Try
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        myConnection.Close()
        MsgBox("done")
    Catch ex As Exception
        MsgBox("error")
    End Try

    Form3.ROOMTextBox.Text = ROOMTextBox.Text
    Me.Validate()
    Me.ROOMSBindingSource.EndEdit()
    Me.TableAdapterManager.UpdateAll(Me.MY_HOTELDataSet)
    Me.Hide()
    Form3.Show()
End Sub

1 个答案:

答案 0 :(得分:0)

有几件事。

  1. 用于ms访问的Ado.NET OleDB提供程序使用?作为参数占位符。它们没有命名,所以完全删除名称,只使用问号。确保参数的顺序与它们在语句中出现的顺序相匹配。
  2. 在vb中连接字符串时,使用&而不是用于组合布尔值的单词AND。我在名称部分之间添加了一个空格,如果这不是您的意图,请将其删除。
  3. 不适用于错误,但我强烈建议您使用using块来确保关闭/处理您的连接。
  4. 更新了相关代码:

    str = "update [ROOMS] set [OCCUPIED] = ?, [occupied by]= ? Where [ROOM] = ?"
    Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)
    ' here the name no longer matters so keep it or drop it up to you as long as the order matches the order in the statement.
    cmd.Parameters.AddWithValue("?status", True)
    cmd.Parameters.AddWithValue("?name", Form3.NAMETextBox.Text  & " " & Form3.SURNAMETextBox.Text)
    cmd.Parameters.AddWithValue("?room", ROOMTextBox.Text)