知道是否存在记录

时间:2016-10-14 13:18:49

标签: database sqlite vbscript

我正在编写一个与SQLite数据库交互的VBS程序,但是当我想知道某条记录是否存在时,我遇到了问题。

这是我的代码:

Dim objConn, objRecordSet, following, today, found, search_value, rst

Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConn = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

'Database connection    
objConn.Open("DRIVER=SQLite3 ODBC Driver;Database=C:\Users\Quentin\Downloads\Quentin-Classementhashtags.db")

following = "youyou"
today = "CURRENT_DATE"

'Search if a record exists
Set rst = objRecordSet.Open "SELECT Name FROM Test WHERE Name = " & "'" & _
          following & "'" & ";", objConn, adOpenStatic, adLockOptimistic

If (rst.EOF) Then
    search_value = 0
Else
    search_value = 1
End If

objRecordSet.Close

'If the record doesn't exist, insert the value of the variable "following"
If search_value = 0 Then
    objRecordSet.Open "INSERT INTO Test (Name, Joined) VALUES " & "('" & _
        following & "', " & today & ");", objConn, adOpenStatic, adLockOptimistic
End If

objConn.Close

当我无条件地测试时,我的INSERT查询有效。

但是,我有一个问题:

Set rst = objRecordSet.Open "SELECT Name FROM Test WHERE Name = " & "'" & _
          following & "'" & ";", objConn, adOpenStatic, adLockOptimistic
  

预期指示结束

我这样做是因为我想在变量中恢复此查询的结果。如果记录存在,则不会发生任何事情(search_value = 1)。否则插入变量following的值。

PS:The link which I used for SQL queries

1 个答案:

答案 0 :(得分:1)

当您打开对数据库的查询时,它会直接将结果存储在记录集对象中。例如:

objRecordSet.Open "Select * from Table", objConn

这会将所有结果存储在objRecordSet

现在让我们来看看你的代码:

Dim objConn, objRecordSet, following, today, found, search_value, rst

Const adOpenStatic = 3
Const adLockOptimistic = 3

Set objConn = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

'Database connection    
objConn.Open("DRIVER=SQLite3 ODBC Driver;Database=C:\Users\Quentin\Downloads\Quentin-Classementhashtags.db")

following = "youyou"
today = "CURRENT_DATE"

'Search if a record exists - Old Version
'Set rst = objRecordSet.Open "SELECT Name FROM Test WHERE Name = '" & _
'          following & "';", objConn, adOpenStatic, adLockOptimistic

'Search if a record exists - New Version
objRecordSet.Open "SELECT Name FROM Test WHERE Name = '" & _
    following & "';", objConn, adOpenStatic, adLockOptimistic

If (objRecordset.EOF) Then
    search_value = 0
Else
    search_value = 1
End If

objRecordSet.Close

'If the record doesn't exist, insert the value of the variable "following"
If search_value = 0 Then
    objRecordSet.Open "INSERT INTO Test (Name, Joined) VALUES " & "('" & _
        following & "', " & today & ");", objConn, adOpenStatic, adLockOptimistic
End If

objConn.Close

试一试,让我知道。