[ASP.NET]StoredProcedure+SqlDataAdapter的使用方法

摘要:[ASP.NET]StoredProcedure+SqlDataAdapter的使用方法

需求:當我們在跟資料庫溝通時使用預存程序的方法


                DataTable Department = new DataTable();
                SqlConnection conn = new SqlConnection();
                conn.ConnectionString = "Connstr";
                SqlDataAdapter cmd = new SqlDataAdapter("nop_AddUser", conn);
                //將運作型態設定為StoredProcedure
                cmd.SelectCommand.CommandType = CommandType.StoredProcedure;
               //將預設參數清空
                SqlParameter workParam = null;
               //input 設定好對應參數
                workParam = cmd.SelectCommand.Parameters.Add("@Name", SqlDbType.NVarChar, 10);
                cmd.SelectCommand.Parameters["@Name"].Value = Name;
                workParam = cmd.SelectCommand.Parameters.Add("@Email", SqlDbType.NVarChar, 50);
                cmd.SelectCommand.Parameters["@Email"].Value = Email;
                workParam = cmd.SelectCommand.Parameters.Add("@Password", SqlDbType.NVarChar, 50);
                cmd.SelectCommand.Parameters["@Password"].Value = FormsAuthentication.HashPasswordForStoringInConfigFile(Password, "MD5");
                workParam = cmd.SelectCommand.Parameters.Add("@Department", SqlDbType.Int);
                cmd.SelectCommand.Parameters["@Department"].Value = int.Parse(department);
                //output
                workParam = cmd.SelectCommand.Parameters.Add("@intresult", SqlDbType.Int);
                workParam.Direction = ParameterDirection.Output;
              //最後再塞入TB  
               cmd.Fill(Department);