写基类时,由于涉及到传参,用的方法只能实现特定的数据库操作,完全违背了基类设计的初衷。
今天组长过来帮忙写好了基类的一个方法,只要传入参数,只调用基类的一个方法就能实现数据库操作啦。
基类中的方法:
public static SqlParameter getPara(string pName,SqlDbType pType)
{
SqlParameter sp = new SqlParameter(pName, pType);
return sp;
}

public void dbExectSqlWithPara(string str,SqlParameter[] p)
{
SqlConnection con = new SqlConnection(strConn);
SqlCommand com = new SqlCommand(str, con);

foreach (SqlParameter pp in p)
{
com.Parameters.Add(pp);
}
con.Open();
com.ExecuteNonQuery();
con.Close();
}
类中的代码:
public void addnews(string title,string content)
{
SqlParameter[] p = new SqlParameter[2];

p[0] = SqlDbHelper.getPara("@title", SqlDbType.VarChar);
p[0].Value = title;
p[1] = SqlDbHelper.getPara("@content", SqlDbType.VarChar);
p[1].Value = content;

sdh.dbExectSqlWithPara("insert into news(NewsTitle,NewsContent) values (@title,@content)",p);
}
页面后台代码:
news sea = new news();
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
sea.addnews(this.TextBox1.Text, this.TextBox2.Text);
Response.Write("OK");
}
这样不管什么样的数据库操作,只用基类中dbExectSqlWithPara,getPara两个方法就能实现了。
而以前只能添一条信息在基类加一个方法或者在数据库中加一个存储过程。
感谢组长放下手上的工作来给我讲解,感谢胡总中午不睡觉帮我分析。让我知道了世界上还有种方法叫传参。
今天组长过来帮忙写好了基类的一个方法,只要传入参数,只调用基类的一个方法就能实现数据库操作啦。
基类中的方法:
public static SqlParameter getPara(string pName,SqlDbType pType)
{
SqlParameter sp = new SqlParameter(pName, pType);
return sp;
}
public void dbExectSqlWithPara(string str,SqlParameter[] p)
{
SqlConnection con = new SqlConnection(strConn);
SqlCommand com = new SqlCommand(str, con);
foreach (SqlParameter pp in p)
{
com.Parameters.Add(pp);
}
con.Open();
com.ExecuteNonQuery();
con.Close();
}
public void addnews(string title,string content)
{
SqlParameter[] p = new SqlParameter[2];
p[0] = SqlDbHelper.getPara("@title", SqlDbType.VarChar);
p[0].Value = title;
p[1] = SqlDbHelper.getPara("@content", SqlDbType.VarChar);
p[1].Value = content;
sdh.dbExectSqlWithPara("insert into news(NewsTitle,NewsContent) values (@title,@content)",p);
}
news sea = new news();
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
sea.addnews(this.TextBox1.Text, this.TextBox2.Text);
Response.Write("OK");
}而以前只能添一条信息在基类加一个方法或者在数据库中加一个存储过程。
感谢组长放下手上的工作来给我讲解,感谢胡总中午不睡觉帮我分析。让我知道了世界上还有种方法叫传参。

浙公网安备 33010602011771号