以下代碼阻止我保存新記錄。如果有人能爲我編輯它,我會很高興。無論記錄是否存在,都會顯示消息「存在記錄」。如何防止保存重複記錄
嘗試
If String.IsNullOrEmpty(subject_id) Or rbnCore.Checked = False And rdbElective.Checked = False Or String.IsNullOrEmpty(username) Or String.IsNullOrEmpty(password) Then
MessageBox.Show("One or more fields have not been left empty.", "Save Error", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
txtSubjectCode.Focus()
Else
If rbnCore.Checked = True Then
subject = "Core"
Else : subject = "Elective"
End If
cmd2 = New SqlCommand("select count(*) from ProgramDetails.Subjects where IdNumber = " & txtIDNumber.Text & " ", cn)
queryResult = cmd2.ExecuteScalar
If queryResult = 0 Then
qry = "Insert into ProgramDetails.Subjects(SubjectCode,SubjectName,SubjectType,UserID,Password)values(@SubjectCode,@SubjectName,@SubjectType,@UserID,@Password)"
cmd = New SqlCommand(qry, cn)
cmd.Parameters.Add(New SqlParameter("@SubjectCode", txtSubjectCode.Text))
cmd.Parameters.Add(New SqlParameter("@SubjectName", txtSubName.Text))
cmd.Parameters.Add(New SqlParameter("@SubjectType", subject))
cmd.Parameters.Add(New SqlParameter("@UserID", txtUserName.Text))
cmd.Parameters.Add(New SqlParameter("@Password", txtPassword.Text))
cmd.ExecuteNonQuery()
MessageBox.Show("Record successfully saved", "Saved", MessageBoxButtons.OK, MessageBoxIcon.Information)
btnSave.Enabled = False
btnClear.Focus()
showgrid()
End If
MessageBox.Show("Record already exists", "Existing record", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
?所以你不希望用戶能夠添加新行?有一個非常簡單的方法來寫... – 2013-02-14 18:51:20
SQL注入的一個很好的組合,並失敗處理測試和插入原子。你想要多少代碼? – HABO 2013-02-14 18:52:24
我希望用戶只能保存新記錄。 – Akaglo 2013-02-14 20:05:33