MS Access 记录数始终为 1,即使没有记录
Posted
技术标签:
【中文标题】MS Access 记录数始终为 1,即使没有记录【英文标题】:MS Access recordcount is always 1 even with no record 【发布时间】:2021-10-14 04:59:00 【问题描述】:我正在使用 MS Access 2010。我正在尝试搜索表并根据名字和姓氏确定记录是否存在,如果记录存在则更新记录,如果不存在,则插入新记录记录。我没有收到任何错误,但即使我输入了我知道表中不存在的名称,我的记录数也始终为 1。
Private Sub txtSearchFirstName_Exit(Cancel As Integer)
Dim strSQL As String
Dim db As Database
Dim rs As DAO.Recordset
Dim recordCount As Long
Set db = CurrentDb
Set rs = Nothing
Stop
''Check if a keyword entered or not
If IsNull(Me.txtSearchlastName) = "" Then
MsgBox "Please type in your search keyword.", vbOKOnly, "Keyword Needed"
Else
strSQL = "SELECT COUNT(*) " & _
"FROM tblBobbettesMarketBulletin_CustNum " & _
"WHERE tblBobbettesMarketBulletin_CustNum.Last = " & Chr(34) & txtSearchlastName & Chr(34) & _
" AND tblBobbettesMarketBulletin_CustNum.First = " & Chr(34) & txtSearchFirstName & Chr(34)
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
If (rs.BOF And rs.EOF) Then
recordCount = 0
Else
rs.MoveLast
recordCount = rs.recordCount
End If
If recordCount > 0 Then MsgBox ("Record exists")
If recordCount = 0 Then MsgBox ("Record does not exist")
rs.Close
Set rs = Nothing
End If
End Sub
【问题讨论】:
记录集包含一条记录,其中一个字段向您显示与您的WHERE
条件匹配的tblBobbettesMarketBulletin_CustNum
记录中的COUNT
。如果没有匹配项,则记录集将包含一条在COUNT
字段中为零的记录。在打开记录集后将Debug.Print rs.Fields(0).Value
添加到您的代码中 --- 也许这将有助于澄清情况。
复习,特别是古斯塔夫回答***.com/questions/6199417/upserting-in-ms-access
谢谢,这很有帮助
谨防 SQL 注入。如果有人输入 Thomas “Tommy”的名字,查询将失败。
【参考方案1】:
@HansUp 完美地描述了您的问题。
如果您想简化代码并使用此功能,请为您的 Count(*) 分配一个字段名称,然后一步查询并使用其值
strSQL = "SELECT COUNT(*) AS NumFound " & _
"FROM tblBobbettesMarketBulletin_CustNum " & _
"WHERE tblBobbettesMarketBulletin_CustNum.Last = " & Chr(34) & txtSearchlastName & Chr(34) & _
" AND tblBobbettesMarketBulletin_CustNum.First = " & Chr(34) & txtSearchFirstName & Chr(34)
Debug.Print strSQL
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
MsgBox ("Found " & rs!NumFound & " Record(s)")
【讨论】:
以上是关于MS Access 记录数始终为 1,即使没有记录的主要内容,如果未能解决你的问题,请参考以下文章