Option Explicit
Private Sub Command1_Click()
Dim TestConn As DAO.Connection
Dim TheCursor As DAO.Recordset
Dim sData1 As String
Dim sData2 As String
' Connect to SQL database
DBEngine.DefaultType = dbUseODBC
DBEngine.Workspaces(0).DefaultCursorDriver = -1
Set TestConn = DBEngine.Workspaces(0).OpenConnection("", _
dbDriverNoPrompt, _
False, _
"ODBC;DSN=<DSN>;UID=<User Name>;PWD=<Password>")
' Create a table and enter data into the table
On Error Resume Next
TestConn.Execute "DROP TABLE MyTable"
On Error GoTo 0
TestConn.Execute "CREATE TABLE MyTable (" _
+ " id int unique, Field1 text NULL , " _
+ " Field2 text null)"
TestConn.Execute "INSERT INTO MyTable (id, Field1, Field2) " _
+ " VALUES (1, '" & "apple" & "', '" & "banana" & "')"
' Select data from the newly inserted record into a Recordset
Set TheCursor = TestConn.OpenRecordset("SELECT * From MyTable " _
+ " WHERE ID = 1", _
dbOpenDynaset, _
dbExecDirect, _
dbReadOnly)
sData1 = TheCursor("Field1")
sData2 = TheCursor("Field2")
' Test to check if data output is the same as the table data
If sData1 <> "apple" Or sData2 <> "banana" Then
MsgBox "Test failed. Data1=" & sData1 & ", Data2=" & sData2
Else
MsgBox "Test succeeded."
End If
End Sub