Search code examples
vb.netoledb

Cell not updated - VB.net, oledb


Ive been wrestling with the code below for a long time now, and just when i thought it works it doesnt, and it doesnt even give me an error.

            Dim sql As String = "UPDATE " & table & " SET ArithmeticScore = @score WHERE DateAscending = " & todaysdate
            Using connection As New OleDbConnection(conn)
                Using command As New OleDbCommand(sql, connection)
                    connection.Open()
                    command.Parameters.Add("@score", OleDbType.Decimal).Value = score
                    MsgBox("score was added = " & score)
                    command.ExecuteNonQuery()
                    connection.Close()
                End Using
            End Using

todaysdate currently holds the value 27/04/2020 as date

conn holds the connection string, table holds the table name.

The messagebox outputs what it is meant to, with score having a decimal value that should be added into the table.

The purpose of this code is to update the ArithmeticScore column in the table, Where DateAscending = 27/04/2020. When the program is finished, and i check the database, the cell remains blank. Why could this be?


Solution

  • This is because executed query can not find required record.
    Try to set correct type for sql parameter for DateAscending column.

    Dim sql As String = 
        $"UPDATE {table} SET ArithmeticScore = @score WHERE DateAscending = @todaysdate"
    
    Using connection As New OleDbConnection(conn)
        Using command As New OleDbCommand(sql, connection)
            command.Parameters.Add("@score", OleDbType.Decimal).Value = score
            command.Parameters.Add("@todaysdate", OleDbType.Date).Value = DateTime.Now.Date
    
            connection.Open()
            Dim affectedRows As Integer = command.ExecuteNonQuery()
    
            ' Check or display that affectedRows is greater than zero
        End Using
    End Using