//数据层
SqlConnection SqlCon = new SqlConnection(ConfigurationManager.AppSettings["ConStr"]);
//判断值是否已经存在
public bool ExecRead(string sqlcmd)
{
SqlCon.Open();
SqlCmd = new SqlCommand(sqlcmd, SqlCon);
SqlDataReader dr = SqlCmd.ExecuteReader();
dr.Read();
bool b;
if (dr.HasRows)
{
b=true;
}
else
{
b=false;
}
SqlCon.Close();
return b;
}
//根据传递过来的SQL语句执行并返回执行结果
public bool ExecRun(string sqlcmd)
{
SqlCon.Open();
SqlCmd = new SqlCommand(sqlcmd, SqlCon);
int i=SqlCmd.ExecuteNonQuery();
SqlCon.Close();
if (i > 0)//i>0代表执行成功
{
return true;
}
else
{
return false;
}
}
//业务层
//接收两个参数,并将参数传递给SQL语句,调用数据层的方法执行该语句
public void InsertInfo(string Class,int type)
{
//这里的db是数据层的一个实例
string sqlcmd1 = "select * from Class where Class='" + Class + "' and Type=" + type ;
if (!db.ExecRead(sqlcmd1))//为真时代表数据已经存在,所以取反
{
string sqlcmd2 = "insert into Class(Class,Type) values('" + Class + "'," + type + ")";
bool b = db.ExecRun(sqlcmd2);
}
}
//表现层
//获取两个TEXTBOX的值传递给业务层
protected void btnAdd_Click(object sender, EventArgs e)
{
string NewClass = txtAddNewClass.Text;
if (NewClass == "" || NewClass == null)
{
WebMessageBox.Show("添加新分类名称未填写");
}
else
{
type = Convert.ToInt32(ddlType.SelectedValue);
op.InsertInfo(NewClass,type);//这里的OP是业务层的一个实例
}
}