0

我正在使用 Vb6 和 Access 2007。我正在将记录添加到来自 vb6 的访问表名称“主题代码”。主题代码表的详细信息如下。

Subjectcode 表:标题(Degree,Branch,Year1,Year2,Semester,Subjectcode,Subjectname,Theory_Practical, Major_Allied_Elective)值(Bsc,computerscience,2001,2004,1,RACS1,Vb6 programming,Theory,Major)

注意:上表中的主键是 Degree,Branch,Year1,Year2,Semester,Subjectcode 我用来从 vb6 向访问表添加条目的代码如下:

    If degree = "" Or branch1 = "" Or year1 = "" Or year2 = "" Or semester = "" Or subcode.Text = "" Or subname.Text = "" Or theory.Text = "" Or major.Text = "" Then
    MsgBox "Fields can't be empty ! All are mandatory!"
    Else
    rs.Open "select * from subjectcode", con, 1, 3
    rs.AddNew
    rs!degree = degree
    rs!branch = branch1
    rs!year1 = year1
    rs!year2 = year2
    rs!semester = semester
    rs!Subjectcode = subcode.Text
    rs!Subjectname = subname.Text
    rs!Theory_Practical = theory.Text
    rs!Major_Allied_Elective = major.Text
    rs.Update
    MsgBox "Successfully Saved !", vbOKOnly + vbInformation, "info"
    rs.Close
    End If

而vb6的那个添加形式的截图在这里:http://tinypic.com/r/w7c7if/6 不存在相同条目时添加记录。如果记录已经存在,它应该说“记录已经存在”,我不知道该怎么做。请各位大神给个思路。

4

2 回答 2

3

编写一个 save 方法来保存您的记录,以及一个在保存数据之前查询数据库并检查现有记录的方法。

Public Sub SaveSubjectCode(ByVal vDegree As String, ByVal vBranch As String, ByVal vYear1 As Integer, ByVal vYear2 As Integer, ByVal vSemester As Integer, ByVal Subjectcode...)

    If (DoesRecordExist(vDegree, vBranch, vYear1, vYear2, vSemester, vSubjectcode) = True Then
        ' Warn the user
        MessageBox("I'm sorry Dave I can't do that. The record already exists.")
    Else
        ' Save the record
    End If

End Sub

Private Function DoesRecordExist(ByVal vDegree as String, ByVal vBranch As String, ByVal vYear1 As Integer, ByVal vYear2 As Long, ByVal vSemester As Integer, ByVal vSubjectcode As String) As Boolean

    RecordSet = query 'Query the database for the existing record
    If RecordSet.BOF And RecordSet.EOF Then
        DoesRecordExist = False
    Else
        DoesRecordExist = True
    End If

End Function

此外,您希望避免选择每条记录的 Select * 查询,除非您真的需要它,因为它可能很慢,并且随着记录数量的增长而变慢。如果你想获取一个记录集来添加一条新记录,你可以包含一个不返回任何记录的 Where 子句"select * from subjectcode WHERE 1 = 2, con, adOpenKeyset, adLockOptimistic

于 2013-01-20T04:40:58.357 回答
2

在表中创建字段时,您指定是否允许重复。然后有问题的添加或更新会引发异常。

SQL DML 如下所示:

ALTER TABLE tblCustomers
    ADD CONSTRAINT CustomerNames UNIQUE
    ([Last Name], [First Name])

还有其他强大的功能,例如检查约束:

ALTER TABLE tblInvoices
    ADD CONSTRAINT CheckAmount
    CHECK (Amount > 0)

约束的一个优点是您的数据库的完整性不会被可能无法进行冗长的资格预审查询(或无法正确实现它们)的流氓应用程序作为人质。另一个是对聊天技术的性能改进以及当有多个更新程序时数据库可以在预限定查询和更新之间更改的事实。

于 2013-01-21T05:14:26.960 回答