Blackjack项目无法更新Access数据库

时间:2017-07-27 12:40:34

标签: vb.net ms-access oledb

我有一个简单的二十一点游戏,我试图通过添加2个简单值来更新数据库。我希望它将用户名和玩家的分数添加到数据库中。

在观看在线教程后,这是我尝试过的代码:

Imports System.Data.OleDb

Public Class Form1

    'for updating database
    Dim provider As String
    Dim dataFile As String
    Dim connString As String
    Dim myConnection As OleDbConnection = New OleDbConnection

   Private Sub ButtonSaveScore_Click(sender As Object, e    As EventArgs) Handles ButtonSaveScore.Click

        provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
        dataFile = "F:\Documents\Class Documents\CSC289 - K6A - Programming Capstone Project\Project\BlackJack\BlackJack\Scoreboard.accdb"
        connString = provider & dataFile
        myConnection.ConnectionString = connString
        myConnection.Open()
        Dim str As String
        str = "Update [Scores] set [UserName] = '" & playerName & "',[Score] =' " & wins & "' where [ID] = NEW"
        Dim cmd As OleDbCommand = New OleDbCommand(str, myConnection)

        Try
            cmd.ExecuteNonQuery()
            cmd.Dispose()
            myConnection.Close()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

    End Sub

我收到错误:

  

未提供一个或多个变量

我第一次点击保存按钮。第二次它打破了应用程序并且它说我“无法调整文件当前状态它已经打开。然后突出显示myConnection.ConnectionString = connString

1 个答案:

答案 0 :(得分:1)

考虑实施Using

  

有时,您的代码需要非托管资源,例如文件句柄,COM包装器或SQL连接。使用块可确保在代码完成后处理一个或多个此类资源。这使得它们可供其他代码使用。

以下是一些示例代码:

Using con As New OleDbConnection(connectionString),
      cmd As New OleDbCommand(commandString, con)

    con.Open()

    cmd.ExecuteNonQuery()

End Using

这将处理关闭和处理对象。

我还会考虑使用参数来避免SQL注入。有关详细信息,请参阅Bobby Tables

以下是一些示例代码:

Using con As New OleDbConnection(connectionString),
      cmd As New OleDbCommand("UPDATE [Scores] SET [UserName] = ?, [Score] = ? WHERE [ID] = ?", con)

    con.Open()

    cmd.Parameters.Add("@Username", OleDbType.[Type]).Value = playerName
    cmd.Parameters.Add("@Score", OleDbType.[Type]).Value = wins

    'I've popped this into a parameter as I'm unsure what it is. I'll leave that for you to decide
    cmd.Parameters.Add("@ID", OleDbType.[Type]).Value = "NEW"

    cmd.ExecuteNonQuery()

End Using
  

请注意,我使用了OleDbType.[Type]。您需要将其替换为您为列指定的数据类型。

使用OleDb参数的顺序很重要,而不是命名。确保创建参数,如上图所示。