项目结构中,app.config文件非常重要.
这里需要给项目中的一些常用的配置信息在app.config中进行配置。
下面是配置文件一部分
1.代码清单:app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="server" value="localhost"></add>
<add key="dbName" value="test"></add>
<add key="user" value="root"></add>
<add key="pwd" value="1234"></add>
</appSettings>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
<supportedRuntime version="v2.0.50727"/>
</startup>
<runtime>
<enforceFIPSPolicy enabled="false"/>
</runtime>
</configuration>
下面讲解如何在代码中使用
MySQLUtil.cs是我对MySQL数据库的封装,主要对执行对数据的操作,其中默认的构造器是通过读取app.config文件中属性的属性值来进行配置的。
2.代码清单:MySQLUtil
public class MySQLUtil : ITestModule
{
private MySQLConnection _conn=null;
/// <summary>
/// 默认无参构造方法
/// </summary>
public MySQLUtil()
{
//此处可以配置默认数据库连接,从app.config中读取
MySQLConnectionString strConn = new MySQLConnectionString(
ConfigurationManager.AppSettings["server"].ToString(),
ConfigurationManager.AppSettings["dbName"].ToString(),
ConfigurationManager.AppSettings["user"].ToString(),
ConfigurationManager.AppSettings["pwd"].ToString()
);
this._conn=new MySQLConnection(strConn.AsString);
}
3.代码片段:
void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;
/// <summary>
/// 使用方法:
/// 1.有参构造建立数据库连接
/// 2.GetCommand方法执行SQL语句
/// 3.打开连接
/// 4.获得DataTable对象
/// 5.关闭连接
/// </summary>
MySQLUtil hlp = new MySQLUtil("localhost","test","root","1234");
int result= hlp.ExecuteNonQuery("update persons set person_age=99 where id=9");
MySQLCommand cmd = hlp.GetCommand("select * from persons");
hlp.OpenConnection();
DataTable dt = MySQLUtil.GetTableFromCommand(cmd);
Report.Log(ReportLevel.Info, "User Code", "Mysql数据库连接"+hlp.ToString(), new RecordItemIndex(0));
int i =1;
foreach( DataRow dr in dt.Rows){
object name = dr["person_name"];
object pass =dr["person_tel"];
object age =dr["person_age"];
Report.Log(ReportLevel.Info, "User Code", "获得用户名"+name.ToString()+"密码"+pass.ToString()+"年龄:"+age.ToString(), new RecordItemIndex(i));
i++;
}
hlp.CloseConnection();
}
4.建立测试集TestCase_for_mysql
5.添加MySQLUtil.cs到测试集中
6.编译并执行该测试集
7.测试报告