1.首先安装mysql数据驱动,qtp在windows系统下操作连接mysql,所以下载mysql-connector-odbc- 5.1.8-win32.msi
下载地址:http://mysql.mirrors.pair.com/Downloads/Connector-ODBC/5.1/mysqlconnector-odbc-5.1.8-win32.msi
2.安装mysql驱动 ,默认安装即可。
3. 添加默认数据源
控制面板->管理工具->数据源ODBC->系统DNS->添加->在“创建数据源”对话框中选择
“Mysql ODBC 5.1 Driver”->完成->进入连接对话框->填写完后点击“test”,看看是否成功,成功后配置完成。
4.qtp脚本实现连接mysql数据库
如果操作了第3步骤,天机了mysql默认数据源,脚本可以写成:
Dim Conn<br>Set Conn=CreateObject("ADODB.Connection")<br>Const ConnectionString="DSN=mysql_Mail;DATABASE=extmail;PWD=123456;PORT=3306;SERVER=192.168.2.52;UID=root"<br>'Const ConnectionString="Driver={Mysql ODBC 5.1 Driver};DATABASE=extmail;PWD=123456;PORT=3306;SERVER=192.168.2.52;UID=root"<br>Conn.Open ConnectionString<br>If Conn.State0 Then<br> Reporter.ReportEvent micPass,"testing","连接数据库成功"<br> else<br> Reporter.ReportEvent micFail,"testing","连接数据库失败"<br>End If
如果没有进行第3个步骤,没有添加默认数据源,可以用普通方式连接
Dim Conn<br>Set Conn=CreateObject("ADODB.Connection")<br>'Const ConnectionString="DSN=mysql_Mail;DATABASE=extmail;PWD=123456;PORT=3306;SERVER=192.168.2.52;UID=root"<br>Const ConnectionString="Driver={Mysql ODBC 5.1 Driver};DATABASE=extmail;PWD=123456;PORT=3306;SERVER=192.168.2.52;UID=root"<br>Conn.Open ConnectionString<br>If Conn.State0 Then<br> Reporter.ReportEvent micPass,"testing","连接数据库成功"<br> else<br> Reporter.ReportEvent micFail,"testing","连接数据库失败"<br>End If
5.qtp脚本实现查询数据库
Dim Conn,str,sql,i,sum<br>Set Conn=CreateObject("ADODB.Connection")'创建数据库实例<br>Const ConnectionString="DSN=mysql_Mail;DATABASE=extmail;PWD=123456;PORT=3306;SERVER=192.168.2.52;UID=root"<br>'Const ConnectionString="Driver={Mysql ODBC 5.1 Driver};DATABASE=extmail;PWD=123456;PORT=3306;SERVER=192.168.2.52;UID=root"<br>Conn.Open ConnectionString<br>If Conn.State0 Then<br> Reporter.ReportEvent micPass,"testing","连接数据库成功"<br> else<br> Reporter.ReportEvent micFail,"testing","连接数据库失败"<br>End If<br><br>Set str=CreateObject("ADODB.Recordset")'创建数据集实例<br><br>'查询数据库<br> sql="Select * from manager where type='postmaster'"<br> str.Open sql,conn,1,1 '1,1表示只读;1,3表示插入数据;2,3表示修改数据<br> str.MoveFirst'使游标指向第一个记录<br>sum=""<br>While Not str.EOF<br> 'msgbox str.Fields("username")<br> For i=0 to str.Fields.Count-1'str.Fields.Count表示字段个数<br> sum=sum & str(i) & " " '把整个记录显示出来<br> Next<br> Print sum & vbCRLF'打印所有查询的记录<br> str.MoveNext'使游标进入下一个<br>Wend<br><br>str.Close '关闭数据集实例<br>Set str=Nothing<br>Conn.Close '关闭数据库实例<br>Set Conn=Nothing