組長幫忙實現了基類傳參無預存程序能多用的資料庫操作

來源:互聯網
上載者:User
寫基類時,由於涉及到傳參,用的方法只能實現特定的資料庫操作,完全違背了基類設計的初衷。
今天組長過來幫忙寫好了基類的一個方法,只要傳入參數,只調用基類的一個方法就能實現資料庫操作啦。
基類中的方法:        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兩個方法就能實現了。
而以前只能添一條資訊在基類加一個方法或者在資料庫中加一個預存程序。

感謝組長放下手上的工作來給我講解,感謝胡總中午不睡覺幫我分析。讓我知道了世界上還有種方法叫傳參。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.