Trouble connecting and querying in ADO - sql-server

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

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

'3704' Operation is not allowed when the object is closed

Dim ConnDB As ADODB.Connection
Dim RecSet As ADODB.Recordset
Dim ConnStr As String
Dim SQL_Query As String
Dim iCols As Integer
Const ClaimSheet = "Sheet1"
Set ConnDB = New ADODB.Connection
Set RecSet = New ADODB.Recordset
Const SQLServer = "*****"
Const SQLDB = "*****"
ConnStr = "Provider=SQLOLEDB.1;Data Source=" & SQLServer & ";" & _
"Initial Catalog=" & SQLDB & ";" & _
"Integrated Security=SSPI;"
ConnDB.ConnectionTimeout = 3
ConnDB.Open ConnStr
ConnDB.CommandTimeout = 30
SQL_Query = "EXEC [dbo].[Pivot_Claims]"
Set RecSet = ConnDB.Execute(SQL_Query)
If Not RecSet.EOF Then
ThisWorkbook.Sheets(ClaimSheet).Range("B6").CopyFromRecordset RecSet
RecSet.Close
Else
MsgBox "No Records Found"
End If
I'm trying to run the above VBA code to execute a stored procedure (Pivot_Claims) and paste the results into ClaimSheet. I am getting the error 'Operation is not allowed when the object is closed.' which pointes to the ' If Not RecSet.EOF Then' line.
You need to turn the count off on the stored proc.
SET NOCOUNT ON

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

I need to insert data into SQL server from Excel using VBA

I need to insert test-vba.xlsx data into SQL server to the particular database
Sub insertion()
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim rsstring As String
Dim m, nrows As Integer
Set wkb = Workbooks("test-vba.xlsx").Worksheets("Sheet1").Activate
sConnString = "Provider=SQLOLEDB;Data Source=PRATEEP-PC\SQLEXPRESS;" & _
"Initial Catalog=PPDS_07Dec_V1_Decomposition;" & _
"Integrated Security=SSPI;"
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
For m = 0 To nrows - 1
Here are a couple ideas.
Sub UpdateTable()
Dim cnn As Object
Dim wbkOpen As Workbook
Dim objfl As Variant
Dim rngName As Range
Workbooks.Open "C:\Users\Excel\Desktop\Excel_to_SQL_Server.xls"
Set wbkOpen = ActiveWorkbook
Sheets("Sheet1").Select
Set rngName = Range(Range("A1"), Range("A1").End(xlToLeft).End(xlDown))
rngName.Name = "TempRange"
strFileName = wbkOpen.FullName
Set cnn = CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFileName & ";Extended Properties=""Excel 12.0 Xml;HDR=Yes"";"
nSQL = "INSERT INTO [odbc;Driver={SQL Server};Server=Server_Name;Database=[Database_Name].[dbo].[TBL]]"
nJOIN = " SELECT * from [TempRange]"
cnn.Execute nSQL & nJOIN
MsgBox "Uploaded Successfully"
wbkOpen.Close
Set wbkOpen = Nothing
End Sub
Sub InsertInto()
'Declare some variables
Dim cnn As adodb.Connection
Dim cmd As adodb.Command
Dim strSQL As String
'Create a new Connection object
Set cnn = New adodb.Connection
'Set the connection string
cnn.ConnectionString = "Server_Name;Database=Database_Name;Trusted_Connection=True;"
'Create a new Command object
Set cmd = New adodb.Command
'Open the connection
cnn.Open
'Associate the command with the connection
cmd.ActiveConnection = cnn
'Tell the Command we are giving it a bit of SQL to run, not a stored procedure
cmd.CommandType = adCmdText
'Create the SQL
strSQL = "UPDATE TBL SET JOIN_DT = 2013-01-13 WHERE EMPID = 2"
'Pass the SQL to the Command object
cmd.CommandText = strSQL
'Open the Connection to the database
cnn.Open
'Execute the bit of SQL to update the database
cmd.Execute
'Close the connection again
cnn.Close
'Remove the objects
Set cmd = Nothing
Set cnn = Nothing
End Sub
Here is another idea.
Sub Button_Click()
'TRUSTED CONNECTION
On Error GoTo errH
Dim con As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strPath As String
Dim intImportRow As Integer
Dim strFirstName, strLastName As String
Dim server, username, password, table, database As String
With Sheets("Sheet1")
server = .TextBox1.Text
table = .TextBox4.Text
database = .TextBox5.Text
If con.State <> 1 Then
con.Open "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & database & ";Integrated Security=SSPI;"
'con.Open
End If
'this is the TRUSTED connection string
Set rs.ActiveConnection = con
'delete all records first if checkbox checked
If .CheckBox1 Then
con.Execute "delete from tbl_demo"
End If
'set first row with records to import
'you could also just loop thru a range if you want.
intImportRow = 10
Do Until .Cells(intImportRow, 1) = ""
strFirstName = .Cells(intImportRow, 1)
strLastName = .Cells(intImportRow, 2)
'insert row into database
con.Execute "insert into tbl_demo (firstname, lastname) values ('" & strFirstName & "', '" & strLastName & "')"
intImportRow = intImportRow + 1
Loop
MsgBox "Done importing", vbInformation
con.Close
Set con = Nothing
End With
Exit Sub
errH:
MsgBox Err.Description
End Sub
Also, check out the links below.
http://www.cnblogs.com/anorthwolf/archive/2012/04/25/2470250.html
http://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm

vb6 ADODB TSQL procedure call quit working after database migration

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.

Resources