vb6 ADODB TSQL procedure call quit working after database migration - sql-server

This code was once working on sql server 2005. Now isolated in a visual basic 6 sub routine using ADODB to connect to a sql server 2008 database it throws an error saying:
"Login failed for user 'admin' "
I have since verified the connection string does work if i replace the body of this sub with the alternative code below this sub. When I run the small program with the button, it stops where it is marked below the asterisk line. Any ideas? thanks in advance.
Private Sub Command1_Click()
Dim cSQLConn As New ADODB.Connection
Dim cmdGetInvoices As New ADODB.Command
Dim myRs As New ADODB.Recordset
Dim dStartDateIn As Date
dStartDateIn = "2010/05/01"
cSQLConn.ConnectionString = "Provider=sqloledb;" _
& "SERVER=NET-BRAIN;" _
& "Database=DB_app;" _
& "User Id=admin;" _
& "Password=mudslinger;"
cSQLConn.Open
cmdGetInvoices.CommandTimeout = 0
sProc = "GetUnconvertedInvoices"
'On Error GoTo GetUnconvertedInvoices_Err
With cmdGetInvoices
.CommandType = adCmdStoredProc
.CommandText = "_sp_cwm5_GetUnCvtdInv"
.Name = "_sp_cwm5_GetUnCvtdInv"
Set oParm1 = .CreateParameter("#StartDate", adDate, adParamInput)
.Parameters.Append oParm1
oParm1.Value = dStartDateIn
.ActiveConnection = cSQLConn
End With
With myRs
.CursorLocation = adUseClient
.LockType = adLockBatchOptimistic
.CursorType = adOpenKeyset
'.CursorType = adOpenStatic
.CacheSize = 5000
'***************************Debug stops here
.Open cmdGetInvoices
End With
If myRs.State = adStateOpen Then
Set GetUnconvertedInvoices = myRs
Else
Set GetUnconvertedInvoices = Nothing
End If
End Sub
Here is the code which validates the connection string is working.
Dim cSQLConn As New ADODB.Connection
Dim cmdGetInvoices As New ADODB.Command
Dim myRs As New ADODB.Recordset
cSQLConn.ConnectionString = "Provider=sqloledb;" _
& "SERVER=NET-BRAIN;" _
& "Database=DB_app;" _
& "User Id=admin;" _
& "Password=mudslinger;"
cSQLConn.Open
cmdGetInvoices.CommandTimeout = 0
sProc = "GetUnconvertedInvoices"
With cmdGetInvoices
.ActiveConnection = cSQLConn
.CommandText = "SELECT top 5 * FROM tarInvoice;"
.CommandType = adCmdText
End With
With myRs
.CursorLocation = adUseClient
.LockType = adLockBatchOptimistic
'.CursorType = adOpenKeyset
.CursorType = adOpenStatic
'.CacheSize = 5000
.Open cmdGetInvoices
End With
If myRs.EOF = False Then
myRs.MoveFirst
Do
MsgBox "Record " & myRs.AbsolutePosition & " " & _
myRs.Fields(0).Name & "=" & myRs.Fields(0) & " " & _
myRs.Fields(1).Name & "=" & myRs.Fields(1)
myRs.MoveNext
Loop Until myRs.EOF = True
End If

This probably shouldn't cause the error you're seeing, but according to http://msdn.microsoft.com/en-us/library/ms677593(VS.85).aspx:
"Only a setting of adOpenStatic is supported if the CursorLocation property is set to adUseClient. If an unsupported value is set, then no error will result; the closest supported CursorType will be used instead."

Turns out it was a linked database permissions error in sql server 2008. I had to delete the link and recreated it with a login/password.

Related

How to get a stored procedure as a text and alter it on another server

I would like to know how to get a stored procedure as a text and update its twin(!) on the other server with an excel macro. So I got this stored procedure on the server which has the newest version of the stored procedure:
Declare #Lines Table (Line NVARCHAR(MAX));
Declare #FullText NVARCHAR(max) = '';
INSERT #Lines EXEC sp_helptext 'StoredProcName';
Select #FullText = #FullText + Line From #Lines;
Select #FullText
#Fulltext has the complete code of 'StoredProcName'. I would like to get this code, cut the first 6 letters (CREATE), append it with "ALTER" and run it on the target server/database to update its twin(!). I got this excel macro to realize it:
Sub GetStoredProcedure()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd1 As ADODB.Command
Set cmd1 = New ADODB.Command
'Getting data from local
Set cn = New ADODB.Connection
cn.ConnectionString = _
"Provider=SQLOLEDB;" & _
"Data Source=myDataSource;" & _
"Initial Catalog=myDataBase;" & _
"Integrated Security=SSPI;"
cn.Open 'Connection establishment.
cmd1.ActiveConnection = cn
cmd1.CommandType = adCmdStoredProc
cmd1.CommandText = "UpdateStoredProcedure"
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
Parameter = Cells(i, 1).Value
cmd1.Parameters.Refresh
cmd1.Parameters("#sPName").Value = Parameter
Set rs = cmd1.Execute
rs.Open
Debug.Print rs.State
Range("K2").CopyFromRecordset rs
Next i
rs.Close 'Deactivating the recordset.
cn.Close 'Deactivating the connetion.
End Sub
After running this macro I get the Run-time error '3704': Operation is not allowed when the object is closed.
Thanks in advance for your help.
Try
Option Explicit
Sub GetStoredProcedure()
Dim cn As ADODB.Connection, rs As ADODB.Recordset
Dim cmd1 As ADODB.Command
'Getting data from local
Set cn = New ADODB.Connection
cn.ConnectionString = _
"Provider=SQLOLEDB;" & _
"Data Source=myDataSource;" & _
"Initial Catalog=myDataBase;" & _
"Integrated Security=SSPI;"
cn.Open 'Connection establishment.
Dim sProc As String, sCode As String, n As Long, i As Long
With Range("K:L")
.Font.Name = "Lucida Console"
.Font.Size = 11
.NumberFormat = "#"
.ColumnWidth = 85
End With
Set cmd1 = New ADODB.Command
With cmd1
.ActiveConnection = cn
.CommandType = adCmdText
For i = 2 To Cells(Rows.Count, 1).End(xlUp).Row
sProc = Cells(i, 1).Value
.CommandText = "EXEC sp_helptext '" & sProc & "';"
Set rs = .Execute
sCode = rs.GetString
sCode = Replace(sCode, vbCrLf & vbCrLf, vbCrLf)
Range("K" & i).Value = sCode
Range("L" & i).Value = Replace(sCode, "CREATE PROCEDURE", "ALTER PROCEDURE")
n = n + 1
Next i
End With
rs.Close 'Deactivating the recordset.
cn.Close 'Deactivating the connetion.
MsgBox n & " procedures", vbInformation
End Sub

Run SQL Server stored procedure from VBA

This is my stored procedure which works fine in SQL Server Management Studio.
exec GroupCommissions #GroupNumberEntry = '01142'
Should produce a table of data.
I'm trying to run it in vba using the following code:
Dim rs As ADODB.Recordset
Dim cnSQL As ADODB.Connection
Dim sqlcommand As ADODB.Command, prm As Object
Set cnSQL = New ADODB.Connection
cnSQL.Open "Provider=SQLOLEDB; Data Source=bddc1didw1;Initial Catalog=Actuarial; Trusted_connection=Yes; Integrated Security='SSPI'"
Set sqlcommand = New ADODB.Command
sqlcommand.ActiveConnection = cnSQL
sqlcommand.CommandType = adCmdStoredProc
sqlcommand.CommandText = "GroupCommissions"
Set prm = sqlcommand.CreateParameter("GroupNumberEntry", adParamInput)
sqlcommand.Parameters.Append prm
sqlcommand.Parameters("GroupNumberEntry").Value = "01142"
Set rs = New ADODB.Recordset
rs.CursorType = adOpenStatic
rs.LockType = adLockOptimistic
rs.Open sqlcommand
ActiveSheet.Range("a3").CopyFromRecordset rs
But it just returns blank and I can't work out what I'm doing wrong. Also is there a simpler way to do this?
As discussed below i've managed to fix the issue by adding SET NOCOUNT ON to the original stored procedure. My issue now is I want to do a second stored procedure in the same code but it only seems to work for one. They both work individually however. So either I have to reopen the connection or use 2 on the defined variables? Here is the code:
Dim rs As ADODB.Recordset
Dim cnSQL As ADODB.Connection
Dim sqlcommand As ADODB.Command, prm As Object, prm2 As Object
Set cnSQL = New ADODB.Connection
cnSQL.Open "Provider=SQLOLEDB; Data Source=bddc1didw1;Initial Catalog=Actuarial; Trusted_connection=Yes; Integrated Security='SSPI'"
Set sqlcommand = New ADODB.Command
sqlcommand.ActiveConnection = cnSQL
'groupdates
sqlcommand.CommandType = adCmdStoredProc
sqlcommand.CommandText = "GroupDate"
Set prm = sqlcommand.CreateParameter("GroupNumberEntry", adVarChar, adParamInput, 5)
Set prm2 = sqlcommand.CreateParameter("ValuationDateEntry", adDate, adParamInput)
sqlcommand.Parameters.Append prm
sqlcommand.Parameters.Append prm2
sqlcommand.Parameters("GroupNumberEntry").Value = "01132"
sqlcommand.Parameters("ValuationDateEntry").Value = "08-31-2019"
Set rs = New ADODB.Recordset
rs.CursorType = adOpenStatic
rs.LockType = adLockOptimistic
rs.Open sqlcommand
ActiveSheet.Range("a2").CopyFromRecordset rs
'GroupCommissions
sqlcommand.CommandType = adCmdStoredProc
sqlcommand.CommandText = "GroupCommissions"
Set prm = sqlcommand.CreateParameter("GroupNumberEntry", adVarChar, adParamInput, 5)
sqlcommand.Parameters.Append prm
sqlcommand.Parameters("GroupNumberEntry").Value = "01132"
Set rs = New ADODB.Recordset
rs.CursorType = adOpenStatic
rs.LockType = adLockOptimistic
rs.Open sqlcommand
ActiveSheet.Range("DB2").CopyFromRecordset rs
Try replacing that line with something like this:
Set prm = sqlcommand.CreateParameter("GroupNumberEntry", adVarChar, GroupNumberEntry, 255)
Set the field type and length according to how your proc is defined.
Your code looked OK to me so I copied it into Excel (2016...) and tried it. It gave me an error on that line but adding the additional parameter values to CreateParameter fixed the issue. shrug It shouldn't matter since those are optional parameters, unless there is something maybe at the provider level.
you can try just sending the SQL PROCEDURE straight through as a CALL function.
Take a look at this:
Public connDB As New ADODB.Connection
Public rs As New ADODB.Recordset
Public strSQL As String
Public strConnectionstring As String
Public strServer As String
Public strDBase As String
Public strUser As String
Public strPwd As String
Public PayrollDate As String
Sub WriteStoredProcedure()
PayrollDate = "2017/05/25"
Call ConnectDatabase
On Error GoTo errSP
strSQL = "EXEC spAgeRange '" & PayrollDate & "'"
connDB.Execute (strSQL)
Exit Sub
errSP:
MsgBox Err.Description
End Sub
Sub ConnectDatabase()
If connDB.State = 1 Then connDB.Close
On Error GoTo ErrConnect
strServer = "SERVERNAME" ‘The name or IP Address of the SQL Server
strDBase = "TestDB"
strUser = "" 'leave this blank for Windows authentication
strPwd = ""
If strPwd > "" Then
strConnectionstring = "DRIVER={SQL Server};Server=" & strServer & ";Database=" & strDBase & ";Uid=" & strUser & ";Pwd=" & strPwd & ";Connection Timeout=30;"
Else
strConnectionstring = "DRIVER={SQL Server};SERVER=" & strServer & ";Trusted_Connection=yes;DATABASE=" & strDBase 'Windows authentication
End If
connDB.ConnectionTimeout = 30
connDB.Open strConnectionstring
Exit Sub
ErrConnect:
MsgBox Err.Description
End Sub

Select long text from SQL using Excel VBA ADO returns garbage characters [duplicate]

This question already has an answer here:
What are the limits for ADO data types?
(1 answer)
Closed 3 years ago.
I can't figure out how to retrieve long text (>8kb) from a SQL Server field using an ADODB connection through Excel VBA. My method returns a garbage string.
I can successfully upload a field with >8kb data length using a parameterized query as in the following code:
Public Sub TestLongParamUploadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "INSERT INTO MYTABLE ([Long_Text], [Table_Index]) VALUES (?, ?);"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
Set Pm = .CreateParameter("long_text", adLongVarWChar, adParamInput, 20000)
Pm.Value = Replace("THIS IS A REALLY LONG TEXT STRING " & Space(8000) & "THIS IS A REALLY LONG TEXT STRING", " ", ".")
.Parameters.Append Pm
Set Pm = .CreateParameter("table_index", adVarChar, adParamInput, 32)
Pm.Value = "MYFAKERECORD"
.Parameters.Append Pm
Set rs = .Execute
End With
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub
But when I attempt to retrieve the data via a SELECT statement, the data comes back garbled.
Public Sub TestLongParamDownloadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "SELECT * FROM MYTABLE WHERE Table_Index='MYFAKERECORD';"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
End With
Set rs = cmd.Execute()
Do Until rs.EOF = True
For i = 0 To rs.Fields.Count - 1
If Not IsNull(rs.Fields.Item(i)) Then
Debug.Print ("field '" & rs.Fields(i).Name & "' length: " & Len(rs.Fields.Item(i)) & "; value: '" & rs.Fields.Item(i) & "'")
End If
Next
rs.MoveNext
Loop
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub
The data is successfully making it into the database. I'm able to open and see it in SQL Server Management Studio.
However. The Debug.Print output from my download looks like the following
field 'Long_Text' length: 8067; value: ' MYFAKERECORD ? ?%0?? ?%0?? ? ? ? ? ?
'
field 'Table_Index' length: 12; value: 'MYFAKERECORD'
Note that the length appears to be correct. It's not merely an issue in printing in the immediate window of the Excel VBA IDE. When I write the data to an excel cell via the macro, the cell contains '``' after upload.
I've tried the upload with the parameter for Unicode adLongVarWChar and plaintext adLongVarChar. Both appear to place data correctly in the database. Both come back as broken text from the select statement.
What is the appropriate way to download and interrogate long text via adodb?
EDIT I did find this thread which notes a fundamental limitation that ADO cannot interpret nvarchar(max) type. The proposed solution of CAST'ing the variable to nvarchar(20000) will not work for me because the upward limit for CAST is 8000 characters. How can I transfer data from a field GREATER than 8kb to Excel VBA?
This answer was drawn from the post What are the limits for ADO data types?
The solution as is to:
Cast the desired fields as text.
Retrieve the actual data from the record set using string = rs.Fields(0).GetChunk(rs.Fields(0).ActualSize)
Incorporating into my code it looks like:
Public Sub TestLongParamDownloadQuery()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim param As ADODB.Parameter
Dim rs As ADODB.Recordset
Query = "SELECT * FROM MYTABLE WHERE Table_Index='MYFAKERECORD';"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
On Error GoTo connerror
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = Query
.CommandType = adCmdText
End With
Set rs = cmd.Execute()
Do Until rs.EOF = True
For i = 0 To rs.Fields.Count - 1
If Not IsNull(rs.Fields.Item(i)) Then
If rs.Fields.Item(i).Name = "Long_Text" Then
Debug.Print(rs.Fields(i).GetChunk(rs.Fields(i).ActualSize))
End If
Debug.Print ("field '" & rs.Fields(i).Name & "' length: " & Len(rs.Fields.Item(i)) & "; value: '" & rs.Fields.Item(i) & "'")
End If
Next
rs.MoveNext
Loop
connerror:
If Err.Number <> 0 Then
Msg = "Error # " & str(Err.Number) & " was generated by " _
& Err.Source & Chr(13) & "Error Line: " & Erl & Chr(13) & Err.Description
MsgBox Msg, , "Error", Err.HelpFile, Err.HelpContext
End If
conn.Close
End Sub

Runtime error 3001 'Arguments are of the wrong type or out of acceptable range...'

I have an Excel table and want to update SQL Server table records' date value (with getdate function) which referred by 12th column of Excel.
My code is as below, but I'm seeing:
Run-time error 3001 Arguments are of the wrong type or out of acceptable range or are in conflict with one another.
In SQL table MODIFIEDDATE field is datetime type, and MAINREF field is integer type.
Private Sub CommandButton2_Click()
Dim conn2 As New ADODB.Connection
Dim rst2 As New ADODB.Recordset
Dim j As Integer
conn2.ConnectionString = "Provider=SQLOLEDB.1;Password=abc;Persist Security Info=True;User ID=sa;Initial Catalog=logodb;Data Source=A3650;Use Procedure for Prepare=1;Auto"
conn2.Open
For j = 0 To 1900
If Sayfa1.Cells(j + 4, 12) = "" Then
Sayfa1.Cells(j + 4, 13) = "empty"
Else
rst2.Open "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF='" & Sayfa1.Cells(j + 4, 12) & "'", conn, 1, 3
rst2.Close
End If
Next j
End Sub
I've tried to change the SQL query like, (CInt(cell.value))
rst2.Open "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF='" & CInt(Sayfa1.Cells(j + 4, 12)) & "'", conn, 1, 3
but, it didn't work.
The ADODB.Recordset object should not be used for an UPDATE query. Execute the SQL statement directly from the ADODB.Connection
Dim conn2 As New ADODB.Connection
conn2.ConnectionString = "Provider=SQLNCLI11;Server=MYSERVER;Database=TMP;UID=sa;password=abc;"
conn2.Open
conn2.Execute "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF=1"
There are a couple of ways you can fulfil your requirements and it seems that you are mixing the two.
One way is to update records one at a time, and to do this you would use the Connection object or, more preferably, the Command object. I say preferably because parameterised commands are a far more robust way of executing your SQL. If you intend to use SQL then it's something you probably ought to read about. The way you would do that is as follows:
Public Sub ParameterisedProcedure()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim v As Variant
Dim j As Integer
'Read the sheet data
v = Sayfa1.Range("L4", "M1904").Value2
'Open the database connection
Set conn = New ADODB.Connection
conn.ConnectionString = "Provider=SQLOLEDB.1;" & _
"Password=abc;" & _
"Persist Security Info=True;" & _
"User ID=sa;" & _
"Initial Catalog=logodb;" & _
"Data Source=A3650;" & _
"Use Procedure for Prepare=1;" & _
"Auto"
conn.Open
'Loop through the values to update records
For j = 1 To UBound(v, 1)
If IsEmpty(v(j, 1)) Then
v(j, 2) = "empty"
Else
'Create the parameterised command
Set cmd = New ADODB.Command
cmd.ActiveConnection = conn
cmd.CommandType = adCmdText
cmd.CommandText = "UPDATE T_015 " & _
"SET MODIFIEDDATE=? " & _
"WHERE MAINREF=?"
prm = cmd.CreateParameter(Type:=adDate, Value:=Now)
cmd.Parameters.Append prm
prm = cmd.CreateParameter(Type:=adInteger, Value:=v(j, 1))
cmd.Parameters.Append prm
cmd.Execute
End If
Next
'Write the updated values
Sayfa1.Range("L4", "M1904").Value = v
'Close the database
Set prm = Nothing
Set cmd = Nothing
conn.Close
End Sub
The other way is to use Transactions and you would indeed use a Recordset for that (ie similar to what you have already done). In this case I'd suggest it is the better way to do it because executing one command at a time (as in the above code) is very slow. A vastly quicker way would be to commit all your updates in one transaction. Like a parameterised command, it's also safe from rogue strings entering your SQL command text. The code would look like this:
Public Sub TransactionProcedure()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmdText As String
Dim v As Variant
Dim j As Integer
'Read the sheet data
v = Sayfa1.Range("L4", "M1904").Value2
'Open the database connection
Set conn = New ADODB.Connection
conn.ConnectionString = "Provider=SQLOLEDB.1;" & _
"Password=abc;" & _
"Persist Security Info=True;" & _
"User ID=sa;" & _
"Initial Catalog=logodb;" & _
"Data Source=A3650;" & _
"Use Procedure for Prepare=1;" & _
"Auto"
conn.Open
'Retrieve the data
Set rs = New ADODB.Recordset
cmdText = "SELECT * FROM T_015"
rs.Open cmdText, conn, adOpenStatic, adLockReadOnly, adCmdText
'Loop through the values to update the recordset
On Error GoTo EH
conn.BeginTrans
For j = 1 To UBound(v, 1)
If IsEmpty(v(j, 1)) Then
v(j, 2) = "empty"
Else
'Find and update the record
rs.Find "MAINREF=" & CStr(v(j, 1))
If Not rs.EOF Then
rs!ModifiedDate = Now
rs.Update
End If
End If
Next
conn.CommitTrans
'Write the updated values
Sayfa1.Range("L4", "M1904").Value = v
'Close the database
rs.Close
conn.Close
Exit Sub
EH:
conn.RollbackTrans
Sayfa1.Range("L4", "M1904").Value = v
rs.Close
conn.Close
MsgBox Err.Description
End Sub

Trouble connecting and querying in ADO

I am making a .MDB file which include a ms access database and a form made with vb 6. I am using ms access 2000, and I need to connect to both my local database in the MDB, and a remote MS SQL 2005 database.
In the below code, I can use a msgbox to display the value return from the result set, but when try to output it in a textBox, e.g: txtStatus.Value = txtStatus.Value & rstRecordSet.Fields(1) & vbCrLf, it just hangs. And the method show in the original example from the tutorial got a method of Debug.Print something, but it turns out didn't do anything which I can see. I mean, VB doesn't have a console panel, where will the print statement goes to?
The code with got error:
Function Testing()
On Error GoTo Error_Handling
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
conConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
App.Path & "\" & CurrentDb.Name & ";"
conConnection.CursorLocation = adUseClient
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
If rstRecordSet.EOF = False Then
rstRecordSet.MoveFirst
Do
MsgBox "Record " & rstRecordSet.AbsolutePosition & " " & _
rstRecordSet.Fields(0).Name & "=" & rstRecordSet.Fields(0) & " " & _
rstRecordSet.Fields(1).Name & "=" & rstRecordSet.Fields(1)
rstRecordSet.MoveNext
Loop Until rstRecordSet.EOF = True
End If
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Function
Error_Handling:
MsgBox "Error during function Testing!"
Exit Function
End Function
I thought it was a joke at the beginning ;-)
Anyway I assume you're talking about ADO, as in your title.
Here you can find stuff.
This site will help you with the connection strings for different database.
The difference between access and sql server using ADO it is exactly the connection string.
I would suggest you to avoid Remote Data Controls cause make your life simpler at the beginning but then you have to struggle with them cause they don't work properly.
This is an example of connection and fetch of data:
Dim cnn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim strSql As String
cnn.ConnectionString = _
"Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=m:\testdbSource\testSource.mdb;" & _
"User Id=admin;Password=;"
cnn.Open
cmd.ActiveConnection = cnn
cmd.CommandType = adCmdText
cmd.CommandText = "select * from tblSource"
cmd.Execute
Set cmd = Nothing
cnn.Close
Set cnn = Nothing
This sample works for me:
Function Testing()
On Error GoTo Error_Handling
Dim MyDb As String
Dim conConnection As New ADODB.Connection
Dim cmdCommand As New ADODB.Command
Dim rstRecordSet As New ADODB.Recordset
MyDb = "db1.mdb"
With conConnection
.Provider = "Microsoft.Jet.OLEDB.4.0"
.ConnectionString = App.Path & "\" & MyDb
.Open
End With
With cmdCommand
.ActiveConnection = conConnection
.CommandText = "SELECT * FROM Opt_In_Customer_Record;"
.CommandType = adCmdText
End With
With rstRecordSet
.CursorType = adOpenStatic
.CursorLocation = adUseClient
.LockType = adLockOptimistic
.Open cmdCommand
End With
Do While Not rstRecordSet.EOF
MsgBox "Record " & rstRecordSet.AbsolutePosition & " " & _
rstRecordSet.Fields(0).Name & "=" & rstRecordSet.Fields(0) & " " & _
rstRecordSet.Fields(1).Name & "=" & rstRecordSet.Fields(1)
rstRecordSet.MoveNext
Loop
conConnection.Close
Set conConnection = Nothing
Set cmdCommand = Nothing
Set rstRecordSet = Nothing
Exit Function
Error_Handling:
MsgBox "Error during function Testing!"
MsgBox Err.Description
End Function

Resources