Monday, April 12, 2010

How to access Database using QTP

Method 1:
Option explicit
Dim connectionObj,recordsetObj,commandObj
Dim connectionStr,queryStr

Set connectionObj=createobject("ADODB.connection")
Set commandObj=createobject("ADODB.command")
Set recordsetObj=createobject("ADODB.recordset")
connectionStr="driver=sql server;server=xyz;database=test;uid=sa;pwd=sa"
queryStr="insert into studentdetails (stdno,stdname,age,groupname,sex,dateofbirth) values (6,'xyz',22,'ijk','M','08/18/80')"


connectionObj.open connectionStr
set commandObj.activeconnection=connectionObj
commandObj.commandtext=queryStr
Set recordsetObj=commandObj.execute
connectionObj.close
'commandObj.close
recordsetObj.close


If you have set of records in result set and if you want to travese through each of these then use below code:

while not recordsetObj.EOF
noRecords=recordsetObj.fields.count 'This finds the no. of columns in result set
var1=recordsetObj("fieldname1").value 'This retrieve the columnname values
var2=recordsetObj("fieldname2").value
recordsetObj.movenext
wend



Method 2
Option explicit
Dim connectionObj,recordsetObj,commandObj
Dim connectionStr,queryStr
Set commandObj=createobject("ADODB.command")
Set recordsetObj=createobject("ADODB.recordset")
connectionStr="driver=sql server;server=xyz;database=test;uid=sa;pwd=sa"
queryStr="insert into studentdetails (stdno,stdname,age,groupname,sex,dateofbirth) values (6,'xyz',22,'ijk','M','08/18/80')"
commandObj.activeconnection=connectionStr
commandObj.commandtext=queryStr
Set recordsetObj=commandObj.execute
'connectionObj.close
'commandObj.close
'recordsetObj.close

No comments: