【问题标题】:"No value given for one or more required parameters" error using OleDbCommand使用 OleDbCommand 时出现“没有为一个或多个必需参数提供值”错误
【发布时间】:2022-01-07 18:56:36
【问题描述】:

我正在尝试使用 VB.net 更新 MS Access 中的记录。此代码将位于“已交付”按钮下。当我尝试运行它时,它显示“没有为一个或多个必需参数提供值”错误。这是我的代码:

Private Const strConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Traicy\Downloads\MWL(11-30-2021)\MadeWithLove\MadeWithLove\MadeWithLove.mdb;"
ReadOnly conn As OleDbConnection = New OleDbConnection(strConn)
Dim cmd As OleDbCommand

Public Sub DeliveredUpdate()
    Const SQL As String = "UPDATE DELIVERY SET delivery_status =  @status"
    cmd = New OleDbCommand(SQL, conn)

    ' Update parameter
    cmd.Parameters.AddWithValue("@status", "Delivered")

    ' Open connection, update, then close connection
    Try
        conn.Open()
        If cmd.ExecuteNonQuery() > 0 Then
            MsgBox("The delivery status was successfully updated.")
        End If
        conn.Close()
    Catch ex As Exception
        MsgBox(ex.Message)
        conn.Close()
    End Try
End Sub

【问题讨论】:

标签: sql vb.net prepared-statement oledb oledbcommand


【解决方案1】:

不要在使用它们的方法之外声明连接或命令。这些数据库对象使用非托管资源。他们在Dispose 方法中释放这些资源。该语言提供了Using 块来处理这个问题。

正如 Andrew Morton 在 cmets 中提到的,您应该有一个 Where 子句来告诉数据库要更新哪条记录。这将包含记录的主键。我猜到了这个领域的名字,OrderID。检查您的数据库中的真实字段名称。

Access 不使用命名参数,但您可以使用名称以提高可读性。只要将参数添加到Parameters 集合中,Access 将能够识别这些参数,它们的顺序与它们在 sql 字符串中出现的顺序相同。在某些数据库中,Add 方法优于 AddWithValue,因为它不会给数据类型留下机会。

最好将数据库代码与用户界面代码分开。如果您想在Catch 中显示消息框,请将Try 块放在 UI 代码中。这样您的函数就可以在网络应用或移动应用中使用而无需重写。

Public Function DeliveredUpdate(ID As Integer) As Integer
    Dim recordsUpdated As Integer
    Dim SQL As String = "UPDATE DELIVERY SET delivery_status =  @status Where OrderID = @Id;"
    Using conn As New OleDbConnection(strConn),
            cmd As New OleDbCommand(SQL, conn)
        cmd.Parameters.Add("@status", OleDbType.VarChar).Value = "Delivered"
        cmd.Parameters.Add("@Id", OleDbType.Integer).Value = ID
        conn.Open()
        recordsUpdated = cmd.ExecuteNonQuery
    End Using 'closes and disposes the command and connection
    Return recordsUpdated
End Function

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim retVal As Integer
    Dim id As Integer = 1 'not sure where you are getting this value from
    Try
        retVal = DeliveredUpdate(id)
    Catch ex As Exception
        MsgBox(ex.Message)
    End Try
    If retVal > 0 Then
        MsgBox("The delivery status was successfully updated.")
    End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多