首先要得到 SqlConnection對象的執行個體 con , 下面會用到(至於怎麼連資料庫,這不用我說了吧)
// sql語句
//SqlCommand cmd = new SqlCommand("select * from bbsboards where boardsortid=1", con);
//SqlDataAdapter ad = new SqlDataAdapter("select * from bbsboards where boardsortid=1", con);
//ad.Fill(ds);
//預存程序
//(1)無參數
//SqlCommand cmd = new SqlCommand("getBoards", con);
//cmd.CommandType = CommandType.StoredProcedure;
//(2)參數(有輸入參數,輸出參數並且有兩個返回結果集)
SqlCommand cmd = new SqlCommand("getBoardsbySortId", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@sortid",1));
//設定輸出參數
SqlParameter sp = new SqlParameter();
sp.DbType = DbType.Int32;
sp.Direction = ParameterDirection.Output;
sp.ParameterName = "@a";
cmd.Parameters.Add(sp);
//設定傳回值
SqlParameter p = new SqlParameter();
p.DbType = DbType.Int32;
p.Direction = ParameterDirection.ReturnValue;
cmd.Parameters.Add(p);
SqlDataReader ad = cmd.ExecuteReader();
this.GridView1.DataSource = ad; //在這裡我直接把結果集綁定在 gridview 上
this.GridView1.DataBind();
//返回多個結果集合
ad.NextResult();
this.GridView2.DataSource = ad; //在這裡我直接把結果集綁定在 gridview 上
this.GridView2.DataBind();
con.Close();
//獲得傳回值(一定要在con.close()後)
p.Value.ToString();
//獲得輸出參數值
sp.Value.ToString();