简体   繁体   中英

VB.NET:Updating record in Ms Access

I am creating an employee timing sheet in which they have to insert their timings through pressing timein and timeout buttons. For timein I am creating a new record in database, for that person, and for timeout I am using UPDATING command to update that existing record. Here is my code:

Dim cb As New OleDb.OleDbCommandBuilder(ssda)
    cb.QuotePrefix = "["
    cb.QuoteSuffix = "]"

    con.ConnectionString = dbProvider & dbSource
    con.Open()
    Dim str As String
    str = "UPDATE emp_timing SET emp_timing.emp_timeout = '" & OnlyTime & "' WHERE (((emp_timing.emp_code)='" & TextBox1.Text & "') AND ((emp_timing.day)=" & Now.ToString("MM/dd/yyyy") & "))"

    Dim cmd As OleDbCommand = New OleDbCommand(str, con)


    Try
        cmd.ExecuteNonQuery()
        cmd.Dispose()
        con.Close()
        MsgBox("Data added")

        TextBox1.Clear()
        TextBox2.Clear()
        TextBox1.Focus()
        ComboBox1.SelectedIndex = -1
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try

My code is working fine but the problem is that it is not updating records in database.

Datatype for fields in Access: emp_code = Number, emp_timeout = Text, day = Date/Time.

As usual this is caused by your code not using the Parameters collection to pass values to the database engine. This is not really understood until you hit a conversion problem as always happens with dates

str = "UPDATE emp_timing SET emp_timeout = @p1 " & _
      "WHERE emp_code = @p2 AND day = @p3"


Using con = new OleDbConnection( dbProvider & dbSource)
Using cmd = New OleDbCommand(str, con)

    con.Open()
    cmd.Parameters.Add("@p1", OleDbType.VarWChar).Value = OnlyTime
    cmd.Parameters.Add("@p2", OleDbType.Integer).Value = Convert.ToInt32(TextBox1.Text)
    cmd.Parameters.Add("@p3", OleDbType.Date).Value = new DateTime(Now.Year, Now.Month, Now.Day)
    Try
        Dim rowsAdded = cmd.ExecuteNonQuery()
        if rowsAdded > 0 Then
            MsgBox("Data added")
            TextBox1.Clear()
            TextBox2.Clear()
            TextBox1.Focus()
            ComboBox1.SelectedIndex = -1
        End If
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try
End Using
End Using

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM