寫基類時,由於涉及到傳參,用的方法只能實現特定的資料庫操作,完全違背了基類設計的初衷。
今天組長過來幫忙寫好了基類的一個方法,只要傳入參數,只調用基類的一個方法就能實現資料庫操作啦。
基類中的方法: 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兩個方法就能實現了。
而以前只能添一條資訊在基類加一個方法或者在資料庫中加一個預存程序。
感謝組長放下手上的工作來給我講解,感謝胡總中午不睡覺幫我分析。讓我知道了世界上還有種方法叫傳參。