Database Checkpoint and QTP Part 3 – Retrieving Data

In Part1 we saw the wizard method to use Database checkpoint.  In Part2 we learned how to connect to a database using scripts in QTP. In this part we will see how we can retrieve data from database using scripts.

Similar to connection object, you can use ADODB.Recordset to get the recordset object.

Set MyRecordSet = CreateObject("ADODB.Recordset")

Before starting let us first understand the properties and methods of recordset object which will help further.

RecordSet PropertiesDescription
AbsolutePagePage of current position
AbsolutePositionCurrent position
ActiveConnectionActive Connection Object
BOFBeginning of File
BookmarkBookmark of current position
CacheSizeNumber of records cached
CursorLocationServer or Client
CursorTypeForward, Static, Dynamic, Keyset
EOFEnd of File
EditModeWhether or not an edit is in progress
FilterWhat kind of records to hide
LockTypeRecord lock type for edits or updates
MaxRecordsMaximum number of records to retrieve
PageCountTotal number of pages
PageSizeNumber of records per page
RecordCountTotal number of records
SourceSource Command Object
StatusStatus of last action

Recordset MethodsDescription
AddNewAdd a new record to the RecordSet
CancelBatchCancel pending batch updates
CancelUpdateCancel pending update
CloneCopy the RecordSet
CloseClose the RecordSet
DeleteDelete current record
GetRowsRetrieve multiple records
MoveMove the record pointer to a specific record
MoveNextMove the record pointer to the next record
MovePreviousMove the record pointer to the previous record
MoveFirstMove the record pointer to the first record
MoveLastmove the record pointer to the last record
NextRecordSetLoad the next RecordSet in a multi-set query
OpenOpen the RecordSet (execute the query)
RequeryRe-execute the last query executed
ResyncSynchronize the data with the server
SupportsDetermine if a feature is supported by provider
UpdateUpdate the current record
UpdateBatchUpdate pending batched record updates

Don’t worry if you feel this listing is too big, you may never use many of these, all this is for your reference in case you need. The most commonly used property and functions are:

  • EOF – to identify no records returned. You run a query and need to determine the pointer is at last record or not or no records has been returned.
  • Open – To retrieve the RecordSet we use open method which requires two arguments – connection object and command object

Syntax for this would be

<RecordSetName>.Open source, connection, cursor, lock, type

  • Source – is actually the command object, it could be a sql statement
  • Connection – is the connection object connecting the database
  • Cursor – optional parameter to define recordset cursor type (default – Forward only)
  • Lock – optional parameter to set the lock type property(default – Read Only)
  • Type – optional parameter to define the command type (default unknown(8))

For example

Set oRecordSet = CreateObject("ADODB.Recordset")
oRecordSet.Open “Select * from Orders”,oConnection, adOpenStatic

here oConnection is connection session to the database , we have used the static cursor which allows us to open the record in readonly mode, and not used a lock type – so it will use the default lock.

a generic function for retrieving the recordset would be like

Function 2

Function getRecordset(strSQL)
	Dim oConnection, oRecordSet
	Set oConnection = CreateObject("ADODB.Connection")
	Set oRecordSet = CreateObject("ADODB.Recordset")
	oConnection = getConnection()
	oRecordSet.Open strSQL,oConnection, adOpenStatic	Set getRecordset = oRecordSet
End Function

Let us now try this to retrieve data from Orders table of Flight application database.

To get the customer name from table Orders with Order Number 1 will need to execute the query –

Select * from Orders where Order_Number = 1

Example 2

Set MyRecordset = getRecordset("Select * from Orders where Order_Number = 1")
If  MyRecordset.EOF <> True  Then
	msgbox MyRecordset.Fields("Customer_Name").Value
End If

Result

clip_image002

In this example we are using the function 2 by passing the required query and we get the result recordset in the MyRecordset object. Then we are checking whether there is some records there or not using the EOF property.

In the same way we can use other methods as well for different operations

Move to next record – We have a method MoveNext which we can use in a loop until the max record in recordset. Below example illustrates the use of this method to get all the records from table

Example 3

Set MyRecordset = getRecordset("Select * from Orders")
Do while MyRecordset.EOF <> True
	print MyRecordset.Fields("Customer_Name").Value
	MyRecordset.MoveNext
Loop

Result

result log

In the same way you can use other methods and properties of RecordSet object to achieve your task. I have listed her some example which you may encounter in your test.

Function 3 – Number of Records We can traverse through all the records in the recordset to get the number of records in recordset.

Function getRecordCount(ByRef RecordSet)
	Dim Rows
	Rows = 0
    	RecordSet.MoveFirst
   	 Do Until RecordSet.EOF
        		Rows = Rows+1
        		RecordSet.MoveNext
    	Loop
   	 getRecordCount = Rows
End Function

Function 4 – Execute Query

If you need to update, insert or delete records from database, you can use this function. But if you are working on the database for application under test, you should not perform such actions until unless it is required or a database used for QTP.

Function ExecuteQuery(strSQL)
   	On Error Resume Next
  	 Set oConnection = CreateObject("ADODB.Connection")
	oConnection = getConnection()
	oConnection.Execute strSQL
	 If Err.Number <> 0 then
        		ExecuteQuery =  False
       		 Exit Function
    	End If
	ExecuteQuery = True
End Function

Example 4 – Retrieve the column names from a table

Set MyRecordset = getRecordset("Select * from Orders")
nColumns = MyRecordset.Fields.Count
For n = 0 to nColumns - 1
	Print MyRecordset.Fields(n).Name
Next

clip_image006

Example 5 – Import Database Table into Data table

‘ Get recordset
Set MyRecordset = getRecordset("Select * from Orders")
‘Get number of columns in table
nColumns = MyRecordset.Fields.Count
‘Add a sheet in your datatable
Datatable.AddSheet ("DBImport")
For n = 0 to nColumns – 1
‘Get column name
		ParamName = MyRecordset.Fields(n).Name
		‘Add DTParameter
		Datatable.GetSheet("DBImport").AddParameter  ParamName,""
		nRow = 1
		MyRecordset.MoveFirst
		‘Retrieve and place data in data table
		Do while MyRecordset.EOF <> True
			Datatable.SetCurrentRow(nRow)
			Datatable(ParamName,"DBImport") = MyRecordset.Fields(ParamName)
			nRow = nRow + 1
			MyRecordset.MoveNext
		Loop
Next

clip_image008

Apart from this, if you need to connect to a excel file using ADODB connection, you will have to specify a different connection string, which will be like

" DRIVER={Microsoft Excel Driver (*.xls)};DBQ= FileName ;Readonly=True"

With this Saket concludes the series on Database Checkpoint and QTP.

QTP PDFHave you downloaded the FREE Optimizing QTP eBook yet? Get It Now!

QTP RSSI'm sure you have already subscribed to our feed but just in case not. I recommend you to subscribe via RSS feed. You can also subscribe by Email and have new QTP articles sent directly to your inbox.

12 comments ↓

#1 sc0507 on 05.31.10 at 21:15

what a great topic and lovely description. Thank you so much as I am trying to learn QTP descriptive programming on my own ..this article is like a step by step manual to get there
I was struggling with DB connections before..looks like I am getting good at it :-) )))

#2 Vijayendra on 06.07.10 at 14:17

Hi Saket,

During run time I could see two properties named “Item” and “Count” of oConnection and oRecordSet objects. Can you please let me know what and how are they used for?

#3 Saket on 06.08.10 at 22:32

Thanks sc0507, I am glad, you found this useful.

Vijayendra – The Count property is the number of items in the property collection. it returns a long value. You can use this value to loop through the collection.
The Item property is used to return a specific member of the Properties Collection.

#4 Kunal on 09.20.10 at 21:31

Thanks for this.. this is really useful..

However, I would like to add.. some examples of using Recordset Methos/Properties would be more helpful.. I tried to find them in QTP help.. could not find them there as well..

#5 Automating MS Word Documents – Part 2 | Learn QTP on 12.01.10 at 13:30

[...] The above example uses WMI to retrieve the system process information and display the details into the document in a table. For more information on WMI scripting please refer earlier post by Ankur – Windows Management Instrumentaion. Same way the data can be displayed from a data source. Refer earlier post by me … to get the data in a data source from a database. [...]

#6 Archana on 12.01.10 at 16:40

Thanks for the valuable input. this is really helpful for people like me , who r getting to know more about database checkpoint.

#7 Saket Kumar on 12.10.10 at 17:26

Thanks Archana, I am glad – this is helpful.

#8 Honey on 02.18.11 at 17:47

Hello,

Indeed this a very good knowledge platform for begineers like me..
Thanks a lot.

Thanks,
Honey

#9 Lora on 08.31.11 at 06:25

Hi Saket,
Thank you for your posts
I have a question
I’m trying to retrieve data from record set. And it’s always failed :-(
It looks like QTP is not recognize a recordset properties (ex: EOF, Movenext, etc). But you use such properties in your examples! Could you tell me what i have to do to make it working? Maybe i need to make references to ado recordset library, but i didn’t find how to do it in QTP. Please give me advice. I’m working with MySQL and QTP 11 (trial version). Thanks, Lora

#10 jo on 10.31.11 at 05:02

hi saket,

i have found this very helpful. but i am stuck at function 2 getrecordset(strsql)

the sql statement i am trying to pass to the funciton is
“select * from orders where order_number = “& ordrno

and i am getting error as wrong no.of variables.

#11 raj on 11.26.11 at 12:25

am gettin general run error

“datatable.getsheet(“DBImport”).addparameter ParamName,”"

#12 raj on 11.26.11 at 12:32

am unable to pull the fields names in datatable “DBImport”
plz help me out

Leave a Comment