Tuesday, March 6, 2012
ADODB.Recordset Invalid Column Name VB6
variable called vcnumber. I'm not sure what the problem is but I keep
getting the error "Invalid Column Name" when I set sqlstring to "select
* from vc_names where vc_case_number =" & vcnumber. If I don't try to
limit the recordset returned and just set sqlstring to "select * from
vc_names", it works. If there is another\better way to do this, I am
open to suggestions. Thanks!
========================================
===================
Public Sub populatename()
Dim adoConnection As ADODB.Connection
Dim adoRecordset As ADODB.Recordset
Dim connectString As String
Dim sqlstring As String
Set adoConnection = CreateObject("ADODB.Connection")
Set adoRecordset = CreateObject("ADODB.Recordset")
connectString = "Provider=SQLOLEDB.1;Password=password;Persist Security
Info=True;User ID=user;Initial Catalog=db;Data Source=server"
adoConnection.Open connectString
sqlstring = "select * from vc_names where vc_case_number =" & vcnumber
adoRecordset.Open sqlstring, adoConnection, adOpenDynamic,
adLockOptimistic
Do Until adoRecordset.EOF
List2.AddItem adoRecordset!first_name & " " & adoRecordset!middle_name
& " " & adoRecordset!last_name
adoRecordset.MoveNext
Loop
adoRecordset.Close
adoConnection.Close
Set adoRecordset = Nothing
Set adoConnection = Nothing
End Sub
========================================
========================if vs_case_number is a char field, remember to add quotes i.e.
sqlstring = "select * from vc_names where vc_case_number = '" &
vcnumber & "'"
Saturday, February 25, 2012
adodb recordset problem
I am trying to access a table that I know exists and has data. But, when I create a recordset and check for RecordCount, I get a result -1 (no records). When I access the same table (using the same program), it reports (and I can view in a dbgrid) 752580 records exist.
Here's some of the code:
The table is originally copied from another database; I use the following code to be sure the previous connection is closed before proceeding.
If Not adoRS Is Nothing Then
If adoRS.State = adStateOpen Then adoRS.Close
Set adoRS = Nothing
End If
If Not DbConn Is Nothing Then
If DbConn.State = adStateOpen Then DbConn.Close
Set DbConn = Nothing
End If
Then a new connection (it works) is opened to access the database with the copied table:
strDbConn = "Provider=SQLNCLI;Integrated Security=SSPI;" & _
"Persist Security Info=False;Database=" & strDbName & ";" & _
"AttachDBFileName=" & DbPath & ";Data Source=.\sqlexpress;" & _
"User Instance=True"
Next I tried to create the recordset:
Set adoNewRS = New ADODB.Recordset 'Set OHLC recordset
Set adoNewRS.ActiveConnection = DestDbConn
adoNewRS.Open TableName, DestDbConn, adOpenDynamic, adLockOptimistic
Next I try to get the RecordCount:
NumRecords = adoNewRS.RecordCount
At this point, NumRecords (and adoNewRS.RecordCount) = -1 (even tho I know there are 752580 records in the table).
In the adoNewRS.Open statement, I also tried using the following sql statement:
sSQL = "SELECT * FROM TableName ORDER BY [DateTime];"
It also returns a recordcount = -1.
Anybody have clue?
While debugging, I noticed that adoNewRS.Open was taking about as long as the SQL query in ssms. So, I added adoNewRS.MoveLast & msgbox adoNewRS!XHigh and it popped up with the correct value. Apparently, the recordset was created correctly but the RecordCount value was wrong (as noted in previous post).
Using this new info, I discovered a PRB:
http://support.microsoft.com/default.aspx?scid=kb;en-us;194973
Apparently, in some cases, CursorLocation = adUseServer returns -1 instead of the correct RecordCount. Changing the value to adUseClient resolved the issue.
ADODB fill recrodset with stored proc
recordset. Code goes something like:
Set SQLCmd = New ADODB.Command
Set SQLCmd.ActiveConnection = SQLConn
Set rs = New ADODB.Recordset
Set rs.ActiveConnection = SQLConn
rs.CursorType = adOpenForwardOnly
SQLCmd.CommandText = "usp_RPT_PForm_SetWhereTableBooks"
SQLCmd.CommandType = adCmdStoredProc
'*** Set up parameters
SQLCmd.Parameters.Refresh
SQLCmd.Parameters(1) = "aaa"
…
SQLCmd.Parameters(6) = 0
Set rs = SQLCmd.Execute
The proc usp_RPT_PForm_SetWhereTableBooks should returns a recordset
Pre tests:
I know the connection is active because when I call
SQLCmd.Parameters.Refresh the parameter list (of 6 items) are created.
I have copied the parameters into the sql query analyzer and records are
returned
The problem is that the recordset is not being filled
Can you tell me what I am missing please.
Thanks in advance,
Stewart RogersDo you have "Set NoCOunt On"
at the beginning of your Stored Proc '
If Not, add it and try again...
"Datasort" wrote:
> I have a ADODB recordset problem. I want to use a stored proc to retrieve
a
> recordset. Code goes something like:
>
> Set SQLCmd = New ADODB.Command
> Set SQLCmd.ActiveConnection = SQLConn
> Set rs = New ADODB.Recordset
> Set rs.ActiveConnection = SQLConn
> rs.CursorType = adOpenForwardOnly
>
> SQLCmd.CommandText = "usp_RPT_PForm_SetWhereTableBooks"
> SQLCmd.CommandType = adCmdStoredProc
> '*** Set up parameters
> SQLCmd.Parameters.Refresh
> SQLCmd.Parameters(1) = "aaa"
> …
> SQLCmd.Parameters(6) = 0
> Set rs = SQLCmd.Execute
> The proc usp_RPT_PForm_SetWhereTableBooks should returns a recordset
> Pre tests:
> I know the connection is active because when I call
> SQLCmd.Parameters.Refresh the parameter list (of 6 items) are created.
> I have copied the parameters into the sql query analyzer and records are
> returned
> The problem is that the recordset is not being filled
> Can you tell me what I am missing please.
> Thanks in advance,
> Stewart Rogers
>|||try this:
Dim rs As Adodb.Recordset
Set rs = new ADODB.Recordset
SQLConn.usp_Rpt_PFrom_SetWhereTableBooks "aaa", rs
I bet that works.
Greg Jackson
Portland, OR|||That did it ... Thanks!!! Can you tell me why it works with nocount on?
"CBretana" wrote:
> Do you have "Set NoCOunt On"
> at the beginning of your Stored Proc '
> If Not, add it and try again...
>
> "Datasort" wrote:
>|||Datasort...
Yes, what's going on is that SQL Server sends the Record count information
ahead of the actual recordset... and ADO is not smart enough to tell the
difference, so it's trying to "Read" the record count info as your recordset
,
and failing... It couldn' be coded to figure this out, because ADO 2.x added
functionality to handle multiple recordsets in one call to the server.
There's a method (on the RecordSet Object) in ADO called .NextRecordset, tha
t
moves to the next one in the sequence, until it retruns null when you call i
t
on the last one.
"Datasort" wrote:
> That did it ... Thanks!!! Can you tell me why it works with nocount on?
> "CBretana" wrote:
>|||And, obviously, adding Set NoCount On, removes this information from the TDS
(Tabular Data Stream), and then all that's sent backto ADO Is the actual
recordset...
"Datasort" wrote:
> That did it ... Thanks!!! Can you tell me why it works with nocount on?
> "CBretana" wrote:
>|||Odd, horribly odd!
That sounds like a bug since the record count is not returned (or was not
returned) as a recordset, it is returned as a message AFAIK. Further, the
record count is returned after the requested recordset, not before since it
doesn't know the count until it has returned the rerdorset.
So, I would prefer to see this regarded as a BIG BAD BUG!
Comments?
- Tim
"CBretana" <cbretana@.areteIndNOSPAM.com> wrote in message
news:C6A14044-735D-4DD7-802D-1BB719A4A40F@.microsoft.com...
> Datasort...
> Yes, what's going on is that SQL Server sends the Record count information
> ahead of the actual recordset... and ADO is not smart enough to tell the
> difference, so it's trying to "Read" the record count info as your
> recordset,
> and failing... It couldn' be coded to figure this out, because ADO 2.x
> added
> functionality to handle multiple recordsets in one call to the server.
> There's a method (on the RecordSet Object) in ADO called .NextRecordset,
> that
> moves to the next one in the sequence, until it retruns null when you call
> it
> on the last one.
> "Datasort" wrote:
>|||this is common and well documented behavior in ado
GAJ|||So its a "feature" then?
"pdxJaxon" <GregoryAJackson@.Hotmail.com> wrote in message
news:%23nc7lqYKFHA.3420@.tk2msftngp13.phx.gbl...
> this is common and well documented behavior in ado
>
> GAJ
>
Friday, February 24, 2012
ADO.NET or OLEDB connection/recordset?
My package needs to be a High Performance (target: 150,000 rows in 30 minutes) ETL solution. We are using all MS technologies - SSIS, SQL 2005, BIDS, etc. I need to loop the recordset executed by a Stored Proc in a Execute SQL Task in a Source Script Component.
If I use an ADO.NET Connection Manager, here is the code in the Source Script Component Public Overrides Sub CreateNewOutputRows()
Code 1
Dim sqlAdapter As New SqlDataAdapter
Dim dataRow As Data.DataRow
Dim ds As DataSet = CType(Me.Variables.rsSomeResultset, DataSet)
sqlAdapter.Fill(ds)
Iget: Error: System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'System.Data.DataSet'.
Code 2
Dim oledbAdapter As New OleDb.OleDbDataAdapter
Dim dataTable As DataTable
oledbAdapter.Fill(dataTable, Me.Variables.rsSomeResultset)
Error: System.ArgumentException: Object is not an ADODB.RecordSet or an ADODB.Record. Parameter name: adodb
It works all right when I use an OLEDB Connection Manager with the second code sample.
Question: In order to extract the maximum performance, wouldn't it be preferred to use ADO.NET with SqlClient Provider in an all SQL Server 2005 environment? Or will an OLEDB Connection provide comparable or equal performance?
If so, what code can I use? Since the recordset returned by the Stored Proc (in the Execute SQL Task) can only be captured in a System.Object variable and you can only use the overload of the Fill() method of the OleDbDataAdapter to accept an ADO Recordset or Record object.
There was a post recently that compared some of the connection types, but thanks to the lovely search functionality, I can't find it. If anyone else has it, please post it to this thread.
In general, I don't think you are going to see a significant performance difference between ADO.NET and OLEDB against SQL Server.
That being said, if you want to do some further research into the problem, try adding a message box to your script to display the type of the variable.
Code Snippet
System.Windows.Forms.MessageBox.Show(Me.Variables.rsSomeResultset.ToString())|||You Code 1 snippet doesn't look right for ADO.NET. You shouldn't be trying to call sqlAdapter.Fill(ds). Try Dim dataTable as DataTable = ds.Tables(0) instead. I'd guess that OLE DB would be faster. Please post your findings.
|||
Do you mean this discussion?
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1985034&SiteID=1
ADO.NET or OLEDB connection/recordset?
My package needs to be a High Performance (target: 150,000 rows in 30 minutes) ETL solution. We are using all MS technologies - SSIS, SQL 2005, BIDS, etc. I need to loop the recordset executed by a Stored Proc in a Execute SQL Task in a Source Script Component.
If I use an ADO.NET Connection Manager, here is the code in the Source Script Component Public Overrides Sub CreateNewOutputRows()
Code 1
Dim sqlAdapter As New SqlDataAdapter
Dim dataRow As Data.DataRow
Dim ds As DataSet = CType(Me.Variables.rsSomeResultset, DataSet)
sqlAdapter.Fill(ds)
Iget: Error: System.InvalidCastException: Unable to cast object of type 'System.Object' to type 'System.Data.DataSet'.
Code 2
Dim oledbAdapter As New OleDb.OleDbDataAdapter
Dim dataTable As DataTable
oledbAdapter.Fill(dataTable, Me.Variables.rsSomeResultset)
Error: System.ArgumentException: Object is not an ADODB.RecordSet or an ADODB.Record. Parameter name: adodb
It works all right when I use an OLEDB Connection Manager with the second code sample.
Question: In order to extract the maximum performance, wouldn't it be preferred to use ADO.NET with SqlClient Provider in an all SQL Server 2005 environment? Or will an OLEDB Connection provide comparable or equal performance?
If so, what code can I use? Since the recordset returned by the Stored Proc (in the Execute SQL Task) can only be captured in a System.Object variable and you can only use the overload of the Fill() method of the OleDbDataAdapter to accept an ADO Recordset or Record object.
There was a post recently that compared some of the connection types, but thanks to the lovely search functionality, I can't find it. If anyone else has it, please post it to this thread.
In general, I don't think you are going to see a significant performance difference between ADO.NET and OLEDB against SQL Server.
That being said, if you want to do some further research into the problem, try adding a message box to your script to display the type of the variable.
Code Snippet
System.Windows.Forms.MessageBox.Show(Me.Variables.rsSomeResultset.ToString())|||You Code 1 snippet doesn't look right for ADO.NET. You shouldn't be trying to call sqlAdapter.Fill(ds). Try Dim dataTable as DataTable = ds.Tables(0) instead. I'd guess that OLE DB would be faster. Please post your findings.
|||
Do you mean this discussion?
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1985034&SiteID=1
ADO, SQL Server 2000 and VB5
When I execute recordset.open VB return error 6 overflow.
Set rsSql = New ADODB.Recordset
rsSql.ActiveConnection = oConn
rsSql.CursorLocation = adUseClient
rsSql.CursorType = adOpenDynamic
rsSql.LockType = adLockPessimistic
rsSql.Index = "ChaveAto"
Sqlquery = "select id_ato from ato where chave_ato = " & "MP00002183200108240120010827PR"
' MsgBox (Sqlquery)
rsSql.Open Sqlqueryif chave_ato is a char/varchar data type you might need to enclose MP00002183200108240120010827PR in quotes.
Ado Xml
Im use the XMLDomDocumentPtr
and then use ADO Recordset.Open method for the XMLDocument.
All this works fine. The only problem i have is it is very slow. It takes 2seconds for just 1000 records which is not good.
Any help is appreciated...My experience with large recordsets mirrors yours; it does get slow (though I generally began experiencing issues at around 10,000 records). The data is being loaded into an object resident in memory. I usually stick to this technique when recordsets are smaller than 1,000 rows.
Regards,
hmscott|||My first observation would have to be that if you are returning rows for the user to peruse, what are the chances that they'll actually look at more than ten? While recordsets can be huge, my users rarely care about sets with more than twelve rows, and never care about more than 25, so a limit of a thousand seems silly to me!
Next order of business is data size... XML tends to produce largish rows, often in the 2Kb to 10 Kb range. If you figure out how much data that amounts to for a thousand rows, your application is having to slog through quite a bit of data, and that data is often coming down a relatively slow line. If this is your case, just moving and reformatting the data takes a while.
While you might be an exception to the rule and have a perfectly valid reason to do what you are doing, nearly every case I've seen where someone complains about performance for this kind of thing has hinged on a design flaw. Please examine what you are doing, and the performance you are complaining about, and if the problem isn't apparent please give more details and I'm sure that someone here can offer you suggestions.
-PatP
Sunday, February 19, 2012
ADO Recordset.find method Criteria
Dim tblBusiness As New ADODB.Recordset
'Make an ADO connection to the database.
cn.ConnectionString = "XXXXXXXXXXXXXX'"
cn.Open
cn.Properties("Current Catalog") = "MyDB"
cmd.ActiveConnection = cn
cmd.CommandType = adCmdText
tblBusiness.Open "tblBusiness", cn, adOpenDynamic, adLockReadOnly
tblBusiness.Find (Criteria, SkipRecords, SearchDirection, Start)
I haven't found anything detailing how to specify the criteria for the find.
Thanks.
My recommendation would be not to use Find, but to use a select
statement with a WHERE clause, selecting only required data. What you
are trying to do is fetch an entire table, then throw away the rows
you don't want. Think for a moment about what happens to the network,
the server, and your client application when the table has 1,000,000
rows. "SELECT <column list> FROM <TableName> WHERE <some
field>=Criteria" is far more efficient than filtering after the fact.
--Mary
On Sat, 8 May 2004 16:31:01 -0700, "DB"
<anonymous@.discussions.microsoft.com> wrote:
>Can you use an adodb.recordset.find method to locate a record on an MS SQL 2000 server table? I can't figure out how to specify the criteria correctly and haven't found any good documentation. Ex:
> Dim tblBusiness As New ADODB.Recordset
>'Make an ADO connection to the database.
> cn.ConnectionString = "XXXXXXXXXXXXXX'"
> cn.Open
> cn.Properties("Current Catalog") = "MyDB"
> cmd.ActiveConnection = cn
> cmd.CommandType = adCmdText
> tblBusiness.Open "tblBusiness", cn, adOpenDynamic, adLockReadOnly
> tblBusiness.Find (Criteria, SkipRecords, SearchDirection, Start)
>I haven't found anything detailing how to specify the criteria for the find.
>Thanks.
ADO Recordset.find method Criteria
000 server table? I can't figure out how to specify the criteria correctly
and haven't found any good documentation. Ex:
Dim tblBusiness As New ADODB.Recordset
'Make an ADO connection to the database.
cn.ConnectionString = "XXXXXXXXXXXXXX'"
cn.Open
cn.Properties("Current Catalog") = "MyDB"
cmd.ActiveConnection = cn
cmd.CommandType = adCmdText
tblBusiness.Open "tblBusiness", cn, adOpenDynamic, adLockReadOnly
tblBusiness.Find (Criteria, SkipRecords, SearchDirection, Start)
I haven't found anything detailing how to specify the criteria for the find.
Thanks.My recommendation would be not to use Find, but to use a select
statement with a WHERE clause, selecting only required data. What you
are trying to do is fetch an entire table, then throw away the rows
you don't want. Think for a moment about what happens to the network,
the server, and your client application when the table has 1,000,000
rows. "SELECT <column list> FROM <TableName> WHERE <some
field>=Criteria" is far more efficient than filtering after the fact.
--Mary
On Sat, 8 May 2004 16:31:01 -0700, "DB"
<anonymous@.discussions.microsoft.com> wrote:
>Can you use an adodb.recordset.find method to locate a record on an MS SQL
2000 server table? I can't figure out how to specify the criteria correctly
and haven't found any good documentation. Ex:
> Dim tblBusiness As New ADODB.Recordset
>'Make an ADO connection to the database.
> cn.ConnectionString = "XXXXXXXXXXXXXX'"
> cn.Open
> cn.Properties("Current Catalog") = "MyDB"
> cmd.ActiveConnection = cn
> cmd.CommandType = adCmdText
> tblBusiness.Open "tblBusiness", cn, adOpenDynamic, adLockReadOnly
> tblBusiness.Find (Criteria, SkipRecords, SearchDirection, Start)
>I haven't found anything detailing how to specify the criteria for the find
.
>Thanks.
ADO Recordset time out during query..PLEASE HELP
I have a large query that takes about a minute to run from the SQL Query
Analyzer. Now when I run the query from VB6 it craps out 30 seconds into it.
Is there a way around this without manipulating my query. I'm attaching the
query maybe you'll see something I can adjust i'm not a SQL guy so my query
may come off as crude but it works.... sort of!

"SELECT Master.* , Projects.VolumeCode as Expr1 FROM Master
INNER JOIN projects ON Master.ProjectNumber = projects.ProjectNumber
WHERE (Master.TSRDate >= CONVERT(DATETIME, '2004-01-01 00:00:00', 102))AND
(Master.TSRDate < CONVERT(DATETIME, '" + NewDateString + "', 102))
AND (Master.TSRDate + Projects.HoldTime < CONVERT(DATETIME, '" +
NewDateString + "', 102)) AND (Master.ProjectNumber >10)
AND (Not (Master.ProjectNumber=5682))
AND (Not (Master.ProjectNumber=4520))
AND (Not (Master.ProjectNumber=5535))
AND (Not (Master.ProjectNumber=6042))
AND (Not (Master.ProjectNumber=5867))
AND (Master.VolumeID Is Null)
ORDER BY Master.recordnumber;"
Thanks
Rob
IT guy!
at very quick glance,
is there a nonclustered index on ProjectNumber column?
is there a clustered index on the recordnumber column?
you might need to check Index Tunning Wizard for suggestions of possible
indexes
"Rob" <Rob@.discussions.microsoft.com> wrote in message
news:C9D32D06-A9E8-450D-B53B-F45860A8D7C3@.microsoft.com...
> PLEASE HELP!
> I have a large query that takes about a minute to run from the SQL Query
> Analyzer. Now when I run the query from VB6 it craps out 30 seconds into
it.
> Is there a way around this without manipulating my query. I'm attaching
the
> query maybe you'll see something I can adjust i'm not a SQL guy so my
query
> may come off as crude but it works.... sort of!

> "SELECT Master.* , Projects.VolumeCode as Expr1 FROM Master
> INNER JOIN projects ON Master.ProjectNumber = projects.ProjectNumber
> WHERE (Master.TSRDate >= CONVERT(DATETIME, '2004-01-01 00:00:00', 102))AND
> (Master.TSRDate < CONVERT(DATETIME, '" + NewDateString + "', 102))
> AND (Master.TSRDate + Projects.HoldTime < CONVERT(DATETIME, '" +
> NewDateString + "', 102)) AND (Master.ProjectNumber >10)
> AND (Not (Master.ProjectNumber=5682))
> AND (Not (Master.ProjectNumber=4520))
> AND (Not (Master.ProjectNumber=5535))
> AND (Not (Master.ProjectNumber=6042))
> AND (Not (Master.ProjectNumber=5867))
> AND (Master.VolumeID Is Null)
> ORDER BY Master.recordnumber;"
> Thanks
> --
> Rob
> IT guy!
|||In addition to tuning the sql statement and making sure that you have
appropriate indexes in place, have you tried increasing the .CommandTimeout
(within your VB code)?
Keith
"Rob" <Rob@.discussions.microsoft.com> wrote in message
news:C9D32D06-A9E8-450D-B53B-F45860A8D7C3@.microsoft.com...
> PLEASE HELP!
> I have a large query that takes about a minute to run from the SQL Query
> Analyzer. Now when I run the query from VB6 it craps out 30 seconds into
it.
> Is there a way around this without manipulating my query. I'm attaching
the
> query maybe you'll see something I can adjust i'm not a SQL guy so my
query
> may come off as crude but it works.... sort of!

> "SELECT Master.* , Projects.VolumeCode as Expr1 FROM Master
> INNER JOIN projects ON Master.ProjectNumber = projects.ProjectNumber
> WHERE (Master.TSRDate >= CONVERT(DATETIME, '2004-01-01 00:00:00', 102))AND
> (Master.TSRDate < CONVERT(DATETIME, '" + NewDateString + "', 102))
> AND (Master.TSRDate + Projects.HoldTime < CONVERT(DATETIME, '" +
> NewDateString + "', 102)) AND (Master.ProjectNumber >10)
> AND (Not (Master.ProjectNumber=5682))
> AND (Not (Master.ProjectNumber=4520))
> AND (Not (Master.ProjectNumber=5535))
> AND (Not (Master.ProjectNumber=6042))
> AND (Not (Master.ProjectNumber=5867))
> AND (Master.VolumeID Is Null)
> ORDER BY Master.recordnumber;"
> Thanks
> --
> Rob
> IT guy!
ADO Recordset result cannot display Chinese
I have created an application that get Chinese data from SQL Server 2000.
I am using ActiveX Data Object 2.5 via ODBC as connection. Most PC work
perfectly. However, there is 1 client PC that cannot display Chinese. It
always show ?. Can anyone give me some tips?
Regards,
Edward HuiIs this a unicode capable client (what version of windows?) with recent
versions of ODBC drivers?
"Edward Hui" <edhui@.asl.com.hk> wrote in message
news:OaUWhmz2DHA.1760@.TK2MSFTNGP10.phx.gbl...
quote:
> Hi all,
> I have created an application that get Chinese data from SQL Server
2000.
quote:
> I am using ActiveX Data Object 2.5 via ODBC as connection. Most PC work
> perfectly. However, there is 1 client PC that cannot display Chinese. It
> always show ?. Can anyone give me some tips?
> Regards,
> Edward Hui
>
ADO Recordset from SQL Task issue
I have a Foreach Loop that enumerates a set of files from an ADO recordset variable which is populated by a preceding SQL task. The query from the task that populates the recordset returns about 200 rows with one varchar field(a file path). The loop is long running, and so far it errors on the connection string populated by the enumeration variable after about an hour. The timeout for the SQL task is set to zero. Could it be the source recordset variable timing out, or could it be that the recordset is too large?
Thanks,
Chris
If it is related to the number of records you could start by limiting the result to 10 records, and add 10 records until you see the problem again.
Also, do you have the latest service pack? Here's a post concerning an issue prior to the service pack.
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=277765&SiteID=1
|||
200 rows is not too large for a recordset.
I am confused. the sql task populates the recordset and the for each loop enumerates the results. I assume that the sql task is outside (before) the loop. so, which is taking a long time? executing the sql command or running over the recordset in the loop?
|||Thanksfor the replies, and yes, the SQL Task populates the ADO recordset
variable before the loop. The loop enumerates the results for about an
hour before it errors out. The error is the same every time, reporting
that the connection string has failed to have been acquired. The
variable for the connection string is populated by enumerating the
recordset. If i change the loop's collection enumerator to a directory,
the loop runs fine.
Thanks for your help,
Chris
|||I'm on a SQL Server 2k5 x86 ,SP1, windows 2000 platform if that helps.
Thanks,
Chris
|||Also, It's definitely not the recordset itself, as I've been able to use the same ADO variable result set to enumerate loops with fewer tasks\are shorter running. Any chance this is a memory leak?
|||
Well, what are you doing with the rows from the recordset? I think the enumerator gives you a fields collection.
in other words, what is in the loop
|||The (one field per) rows from the recordset enumerate the collection, a directory of Access databases. Inside the Foreach loop are several data flow tasks. A variable is mapped from the returned row and helps populate a connection string expression for an Access connection manager. The source connection for each data flow task uses the connection manager. It works great for about an hour when i use the recordset as a collection enumerator, and the loop does not error out if I use the directory as a collection enumerator.Thanks,
Chris
|||
This is odd. there certainly could be a bug somewhere in the recordset object itself (in the interest of full disclosure, I wrote the code for the ADO Recordset object back in '96 :) )
If you don't mind doing some experiments for me, I would ask you to try to separate the recordset usage from the pipeline usage as a way to try to narrow down the problem. it sounds like you have done this a bit.
instead of a dataflow task, put a script task in the loop. extract the value of the connection string and write it out somewhere so that you can see the values and make sure they all look rational. If this loop completes without error, then add some long delay (like a 5 minute wait) into the script task. this will tell us if their is some purely time related issue with the recordset (doubtful, but who knows could be a garbage collector kicking in and dropping references to the com objects of the recordset? crazy i know).
You say you can use a non-recordset list of the same exact connections and get this to succeed? that makes me think that this is not an issue with the access driver, but who knows. Exactly what error are you getting when it fails?
These two things just don't seem related.
ADO recordset field limitations
Here's the line in question:
rs!ServerMessage = Data
It appears that when my data string is longer that 255 characters, it only
inserts the first 255 characters into the table and throws the rest away
without any errors. The SQL column is defined as varchar(5000).
Any ideas as to how I can get the full string into the database?
MS SQL 2000, VB6
Thanks,
StephenThree words: show more code.
Send us your DDL, your code, and then maybe we can see the problem.
ML|||The code below is collected from several different locations in the app.
Hopefully this is what you need.
Dim cn As ADODB.Connection
Dim provStr As String
Dim strSQL As String
Dim rs As ADODB.Recordset
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
cn.Provider = "sqloledb"
provStr = " Provider=SQLOLEDB;Server=xxxxx;Database=
xxxxx;User
Id=xxxxx;Password = xxxxx"
cn.Open provStr
Set rs.ActiveConnection = cn
rs.CursorType = adOpenKeyset
rs.LockType = adLockOptimistic
Set rs.ActiveConnection = cn
rs.Open "Events", cn, , , adCmdTable
rs.AddNew
rs!ServerName = sName
rs!ServerIP = RemoteIP
rs!ServerMessage = Data
rs!DateTime = Date & " " & Time
rs.Update
If rs.State Then
rs.Close
End If|||Any special reason for not using stored procedures?
I don't see the Data variable being declared. Can it be that its length is
255 bytes?
Incidentally - 'Date & " " & Time' ? Please, use appropriate datatypes! The
Universe will be grateful...
ML|||I have verified that the Data variable does hold the complete string. But it
doesn't end up in the database.
>The Universe will be grateful...
Isn't that a little overboard?|||How are you determining that you only see 255 characters?
If you are doing it though query analyzer, be default each column will only
show 255 characters.
To change this, in QA Tools>Options, Results Tab, Maximum Characters per
Column
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Stephen" <Stephen@.discussions.microsoft.com> wrote in message
news:1FFC354E-2762-4D2D-BD3D-1F2DF1E81D5E@.microsoft.com...
>I am having trouble inserting a record into SQL using an ADO recordset.
> Here's the line in question:
> rs!ServerMessage = Data
> It appears that when my data string is longer that 255 characters, it only
> inserts the first 255 characters into the table and throws the rest away
> without any errors. The SQL column is defined as varchar(5000).
> Any ideas as to how I can get the full string into the database?
> MS SQL 2000, VB6
> Thanks,
> Stephen|||Luckily ML answered and not CELKO, then it would have been a right royal
chewing-out.
:)
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Stephen" <Stephen@.discussions.microsoft.com> wrote in message
news:C9556212-5C24-490A-81F4-C6EB84289192@.microsoft.com...
>I have verified that the Data variable does hold the complete string. But
>it
> doesn't end up in the database.
>
> Isn't that a little overboard?
>|||> It appears that when my data string is longer that 255 characters, it only
> inserts the first 255 characters
What does "appears" mean? What tool are you using to verify the length of
the data? Have you checked SELECT LEN(column) FROM table, and not just the
string result?|||That was exactly the problem. I increased the maximum characters, and saw al
l
of the information.
Thank you for taking the time to help me out.
"Mike Epprecht (SQL MVP)" wrote:
> How are you determining that you only see 255 characters?
> If you are doing it though query analyzer, be default each column will onl
y
> show 255 characters.
> To change this, in QA Tools>Options, Results Tab, Maximum Characters per
> Column
> Regards
> --
> Mike Epprecht, Microsoft SQL Server MVP
> Zurich, Switzerland
> IM: mike@.epprecht.net
> MVP Program: http://www.microsoft.com/mvp
> Blog: http://www.msmvps.com/epprecht/
> "Stephen" <Stephen@.discussions.microsoft.com> wrote in message
> news:1FFC354E-2762-4D2D-BD3D-1F2DF1E81D5E@.microsoft.com...
>
>|||I ran the Len(column) as you suggested and many of the values returned were
well over 255 characters. Mike helped me out by suggesting increasing the
maximum characters in query analyzer. Then I was able to see all of the data
.
Thanks.
"Aaron Bertrand [SQL Server MVP]" wrote:
> What does "appears" mean? What tool are you using to verify the length of
> the data? Have you checked SELECT LEN(column) FROM table, and not just th
e
> string result?
>
>
Thursday, February 16, 2012
ADO Disconnected Recordset
This is a C++ / ADO / SQL question. Maybe not the right forum but I am guessing there are some programmers out there ...
I am trying to use ADO disconnected recordset to insert data into a sql table. I am using AddNew(vField, vValue) with UpdateBatch(). The code below does not throw any exceptions ... but does not add data to the table.
Any comments are appreciated,
Thanks,
Chris
void CTestApp::TestDatabaseUpdateBatch1a(void)
{
int nDataCount = 0;
long nIndex = 0;
long nIndex2 = 0;
CString csMessage;
CString csErrorMessage;
CString csTemp;
CString csSQL;
BOOL bIsOpen;
BOOL bIsEmpty;
long nCount = 0;
int nTemp = 0;
int nLimit = 0;
int nTempInt = 0;
long nTempLong = 0;
double nTempDouble = 0;
HRESULT hResult;
SYSTEMTIME st;
int i = 0;
string strTemp;
_variant_t sval;
_variant_t vNull;
vNull.vt = VT_ERROR;
vNull.scode = DISP_E_PARAMNOTFOUND;
COleSafeArray colesaFieldList;
COleSafeArray colesaDataList;
vector<COleSafeArray> *pvecDataList;
pvecDataList = new vector<COleSafeArray>;
COleDateTime oledtCurrentDate = COleDateTime::GetCurrentTime();
// Convert the OleDateTime to the varient
// COleVariant vCurrentDateTime(oledtCurrentDate);
COleVariant vCurrentDateTime;
CMxTextParse *pMxTextParse = NULL;
CMainFrame *pMainFrame = (CMainFrame *)AfxGetMainWnd();
CFrameWnd* pChild = pMainFrame->GetActiveFrame();
CTestMeteorlogixView* pView = (CTestMeteorlogixView*)pChild->GetActiveView();
pView->WriteLog("Start TestDatabaseUpdateBatch1a.");
pView->WriteLog("Load table using AddNew() and UpdateBatch().");
// Define ADO connection pointers
_ConnectionPtr pConnection = NULL;
_RecordsetPtr pRecordset = NULL;
try
{
// When we open the application we will open the ADO connection
pConnection.CreateInstance(__uuidof(Connection));
// Replace Data Source value with your server name.
bstr_t bstrConnect("Provider='sqloledb';Data Source='SQLDEV';"
"Initial Catalog='AlphaNumericData';"
"User Id=cmacgowan;Password=cmacgowan");
// Open the ado connection
pConnection->Open(bstrConnect,"","",adConnectUnspecified);
// Create an instance of the database
pRecordset.CreateInstance(__uuidof(Recordset));
// Select the correct sql string. Note that we are creating an
// empty string by doing a select on the primary key. We are only
// doing inserts and we do not want to bring data back from the
// server
csSQL = "SELECT * FROM dbo.AAMacgowanTest WHERE RecordId IS NULL";
// csSQL = "SELECT * FROM dbo.DICastRaw1Hr";
pRecordset->PutRefActiveConnection(pConnection);
pRecordset->CursorLocation = adUseClient;
pRecordset->Open(csSQL.AllocSysString(), vNull, adOpenStatic, adLockOptimistic, -1);
// Test to see if the recordset is connected
if(pRecordset->GetState() != adStateClosed)
{
// The recordset is connected, we will see if we are
// at the end
if((pRecordset->BOF) && (pRecordset->GetadoEOF()))
{
// The recordset is empty
bIsEmpty = false;
}
if(pRecordset->GetadoEOF())
{
bIsOpen = false;
}
else
{
// disconnect the database
pRecordset->PutRefActiveConnection(NULL);
}
}
// disconnect the database
// pRecordset->PutRefActiveConnection(NULL);
// Disassociate the connection from the recordset.
pRecordset->PutRefActiveConnection(NULL);
// Set the count
nCount = 1;
// now we will scroll through the file
while(nCount > 0)
{
nCount--;
nDataCount = 10;
// test that we got some data
if (nDataCount >= 0)
{
// Start the insert process
// m_pRecordset->AddNew();
COleSafeArray warningList;
//int index, listIndex = -1, bitIndex; // indexing variables
// long lowIndex, highIndex, arrayIndex[2];
VARIANT vFieldList[25];
VARIANT vValueList[25];
int nFieldIndex = 0;
int nValueIndex = 0;
// Setup the fields
vFieldList[nFieldIndex].vt = VT_BSTR;
vFieldList[nFieldIndex].bstrVal = ::SysAllocString(L"Name");
nFieldIndex++;
vFieldList[nFieldIndex].vt = VT_BSTR;
vFieldList[nFieldIndex].bstrVal = ::SysAllocString(L"Section");
nFieldIndex++;
vFieldList[nFieldIndex].vt = VT_BSTR;
vFieldList[nFieldIndex].bstrVal = ::SysAllocString(L"Code");
nFieldIndex++;
vFieldList[nFieldIndex].vt = VT_BSTR;
vFieldList[nFieldIndex].bstrVal = ::SysAllocString(L"Latitude");
nFieldIndex++;
vFieldList[nFieldIndex].vt = VT_BSTR;
vFieldList[nFieldIndex].bstrVal = ::SysAllocString(L"Longitude");
nFieldIndex++;
pView->WriteLog("Set data using AddNew() ...");
// COleDateTime is a wrapper for VARIANT's DATE type. COleVariant is
// a wrapper for VARIANTs themselves. If you need to create a
// variant, you can say:
COleDateTime oledtCurrentDate2 = COleDateTime::GetCurrentTime();
// Convert the OleDateTime to the varient
COleVariant vCurrentDateTime2(oledtCurrentDate2);
//Set the DATE variant data type.
memset(&st, 0, sizeof(SYSTEMTIME));
st.wYear = 2000;
st.wMonth = 1;
st.wDay = 1;
st.wHour = 12;
// vect is a vector of COleSafeArrays containing the records
for(i = 0; i < 10; i++)
{
// Setup the data
nValueIndex = 0;
vValueList[nValueIndex].vt = VT_BSTR;
vValueList[nValueIndex].bstrVal = ::SysAllocString(L"BLUE");
nValueIndex++;
vValueList[nValueIndex].vt = VT_BSTR;
vValueList[nValueIndex].bstrVal = ::SysAllocString(L"KSTP");
nValueIndex++;
vValueList[nValueIndex].vt = VT_I4;
vValueList[nValueIndex].dblVal = 100 + nFieldIndex;
nValueIndex++;
vValueList[nValueIndex].vt = VT_R8;
vValueList[nValueIndex].dblVal = 11.11 + nFieldIndex;
nValueIndex++;
vValueList[nValueIndex].vt = VT_R8;
vValueList[nValueIndex].dblVal = 22.22 + nFieldIndex;
nValueIndex++;
// Add the record to the recordset
pRecordset->AddNew(vFieldList, vValueList);
}
pView->WriteLog("Call UpdateBatch().");
// Re-connect.
pRecordset->PutRefActiveConnection(pConnection);
// Send updates.
pRecordset->UpdateBatch(adAffectAll);
// Close the recordset and the connection
pRecordset->Close();
pConnection->Close();
}
}
}
catch(_com_error *e)
{
CString Error = e->ErrorMessage();
AfxMessageBox(e->ErrorMessage());
pView->WriteLog("Error processing TestDatabase().");
}
catch(...)
{
csMessage = "Undefined exception handled. Error message details \n\n";
hResult = GetAdoErrorMessage(m_pConnection,
&csErrorMessage);
csMessage += csErrorMessage;
csMessage += "\nmethod: CTestMeteorlogixApp::OnTestDatabaseAdoBulkload()";
AfxMessageBox(csMessage);
}
csTemp.Format("Last Row %03d DIcastId = %s ", nIndex, strTemp.c_str());
pView->WriteLog(csTemp);
pView->WriteLog("End TestDatabaseUpdateBatch1.");
}Yup...wrong forum...
Why not use Stored procedures though?|||Have you checked the errors (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdcolerrors.asp) collection after calling UpdateBatch (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmthupdatebatch.asp)? Check out the VC example (http://msdn.microsoft.com/library/default.asp?url=/library/en-us/ado270/htm/mdmthupdatebatchxvc.asp) to see how they handle the errors.
-PatP|||Originally posted by Brett Kaiser
Yup...wrong forum...
Why not use Stored procedures though?
Thanks for the response. Currently we are using a BULK INSERT to get about 100,000 rows / 30 columns into a table ... then calling a Stored Procedure to do some derivations on the data and populating another table with the results.
We have lots of 'stuff' working on the SQL server and are looking to move some of the business rules from the server to the middle tier. The entire process described above takes about 10-15 minutes and if we could get that type of performace in ADO on the C++ side then we would be happy.
Any comments / suggestions are appreciated
Thanks,
Chris