How can I insert a value in a specified column together with the other columns without appearing it into a new another row alone?

后端 未结 1 431
长情又很酷
长情又很酷 2021-01-29 15:23

I am creating a login logout system for our College Library that records the students\' time in and time out whenever they enter or exit in our library.

I am using VS 20

相关标签:
1条回答
  • 2021-01-29 16:10

    You need to use UPDATE, not INSERT. Assuming they are not able to log out unless they have logged in (i.e. there is record in tblCollegeStudentLog where StudentTimeIn is NULL, you can just use:

    UPDATE  tblCollegeStudentLog
    SET     StudentTimeOut = @OutTime
    WHERE   StudentNumber = @StudentNumber
    AND     StudentTimeOut IS NULL;
    

    Then you would use SqlParameters to properly execute the command and not leave yourself vunerable to SqlInjection, poor SQL Plan caching and data type issues:

    Dim Sql as String = "UPDATE tblCollegeStudentLog SET StudentTimeOut = @OutTime WHERE StudentNumber = @StudentNumber AND StudentTimeOut IS NULL;"
    Using cmd = New SqlCommand(Sql, con)
        cmd.Parameters.AddWithValue("@OutTime", Convert.ToDateTime(lblTimeOutNya.Text))
        cmd.Parameters.AddWithValue("@StudentNumber", lvwLog.SelectedItems(0).Text)
        con.Open()
        If cmd.ExecuteNonQuery() = 0 Then
            'If no rows are affected then there was not a valid
            'record to update, i.e. the student was not logged in
            MsgBox("You were not logged in")
        Else
            MsgBox("You are now logged out!")
        End If
    End Using
    

    N.B. Please excuse my VB.NET, I have not used it in quite some time so there may be some syntax errors.

    0 讨论(0)
提交回复
热议问题