1. 程式人生 > >【C#機房重構】 結賬---儲存過程幫了大忙了!

【C#機房重構】 結賬---儲存過程幫了大忙了!

前言

之前在用vb做機房收費系統的時候,結賬部分呼叫了大量的資料庫中的表,非常之麻煩,這次是用七層的方式進行重構,如果還是按照固有的七個層次去呼叫表,想想就得瘋!最後小編通過查詢資料,利用儲存過程可以減少超多的程式碼量!
所以當我們要操作多個表的時候,我們需要想想儲存過程嘍!

在結賬之前,我們要有流程圖,涉及到幾個表,這個在之前的vb的專案畫過,很麻煩,這裡給一個部落格連結https://blog.csdn.net/jerry11112/article/details/78759788!裡邊有個超大的流程圖!

接下來我們分析,對資料庫的操作無非是增刪改查,我們可以通過儲存過程進行分塊化!

IDAL層

    //查詢資訊
    DataTable SelectInfo(Entity.SettleCount count);//包含衝值表,退卡表

    // 查詢使用者的id
    DataTable SelectUserInfo(Entity.SettleCount count);

    //查詢實際總的消費金額
    DataTable SelectConsumeCash(Entity.SettleCount count);

    //更新需要更新的所有表
    int updateInfo(Entity.SettleCount count);
	//同時更新充值表,學生表,退卡表,line表

儲存過程

(不同的@count在UI層執行不同的sql語句)

USE [charge_sys]
GO
/****** Object:  StoredProcedure [dbo].[PROC_SettleAccount]    Script Date: 2018/8/30 11:08:09 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:		李光
-- Create date: 2018-8
-- Description:	Settlaccounts
-- =============================================
ALTER PROCEDURE [dbo].[PROC_SettleAccount]
	-- Add the parameters for the stored procedure here
	@Count int,
	@RechargeCash numeric(10,2),
	@CancelCash numeric(10,2),
	@ConsumeCash numeric(10,2),
	@AllCash numeric(10,2),
	@date date,
	
[email protected]
nvarchar(50), @UserID nvarchar(50) AS declare @IsCheck char(10) BEGIN SET NOCOUNT ON; set @IsCheck='未結賬' --充值情況: if @Count=1 begin select cardNo,addmoney,date,time from Recharge_Info where status='未結賬' and [email protected] end --退卡情況: if @Count=2 begin select cardNo,CancelCash,date,time from CancelCard_Info where status='未結賬' and
[email protected]
end ----更新情況: if @Count=3 begin update student_Info set status='結賬' where [email protected] update Recharge_Info set status='結賬' where [email protected] and [email protected] update CancelCard_Info set status='結賬' where [email protected] and status [email protected] update Line_Info set Ischeck='結賬' where Ischeck [email protected] insert into checkWeek_Info values (@RechargeCash,@ConsumeCash,@CancelCash,@AllCash,@date,@UserID) end END

D層

public class SettleCountDAL:IDAL.SettleCountIDAL
    {
        public DataTable SelectInfo(Entity.SettleCount count)
        {
            SqlHelper sqlhelper = new SqlHelper();
            SqlParameter[] sqlparams = { new SqlParameter("@UserID",count.UserID),
                                         new SqlParameter("@RechargeCash",count.RechargeCash),
                                         new SqlParameter("@ConsumeCash",count.ConsumeCash),
                                         new SqlParameter("@CancelCash",count.CancelCash),
                                         new SqlParameter("@AllCash",count.AllCash),
                                         new SqlParameter("@date",count.Date),
                                         new SqlParameter("@Count",count.count)
        };
            string sql = "PROC_SettleAccount";
            DataTable dt = sqlhelper.ExecuteQuery(sql, sqlparams, CommandType.StoredProcedure);
            return dt;
             
        }

        public int updateInfo(Entity.SettleCount count)
        {
            SqlHelper sqlhelper = new SqlHelper();
            SqlParameter[] sqlparams = { new SqlParameter("@UserID",count.UserID),
                                         new SqlParameter("@RechargeCash",count.RechargeCash),
                                         new SqlParameter("@ConsumeCash",count.ConsumeCash),
                                         new SqlParameter("@CancelCash",count.CancelCash),
                                         new SqlParameter("@AllCash",count.AllCash),
                                         new SqlParameter("@date",count.Date),
                                         new SqlParameter("@Count",count.count)
        };

            string sql = "PROC_SettleAccount";
            int result = sqlhelper.ExecuteNonQuery(sql, sqlparams, CommandType.StoredProcedure);
            return result;
        }
        //查詢操作員的使用者id和姓名
        public DataTable SelectUserInfo(Entity.SettleCount count)
        {
            SqlHelper sqlhelper = new SqlHelper();
            SqlParameter[] sqlparams = { new SqlParameter("@Level", "操作員") };
            string sql = "SELECT * FROM User_Info WHERE [email protected]";
            DataTable dt = sqlhelper.ExecuteQuery(sql,sqlparams, CommandType.Text);
            return dt;
        }

      public  DataTable SelectConsumeCash(Entity.SettleCount count)
        {
            SqlHelper sqlhelper = new SqlHelper();
            SqlParameter[] sqlparams = { new SqlParameter("@Ischeck", "未結賬") };
            string sql = "SELECT sum(consume) FROM Line_Info WHERE [email protected]";
            DataTable dt = sqlhelper.ExecuteQuery(sql,sqlparams,CommandType.Text);
            return dt;
        }
    }

UI層

  public partial class frmSettleAccounts : Form
    {
        public frmSettleAccounts()
        {
            InitializeComponent();
            tabControl1.Enabled = false;
        }

        #region 定義變數

        Entity.SettleCount Account = new Entity.SettleCount();
        Facade.SettleAountFacade FSettleAcount = new Facade.SettleAountFacade();

        Dictionary<string, string> dic = new Dictionary<string, string>(); //定義一個字典

        double sumCancel = 0;      //計算退卡總金額
        double sumRecharge = 0;   //計算充值總金額 
        #endregion


        #region 載入窗體
        private void frmSettleAccounts_Load(object sender, EventArgs e)
        {
            //表userinfo
            Facade.SettleAountFacade FOpeInfo = new Facade.SettleAountFacade();
            DataTable tableOpeinfo = FOpeInfo.selectOpeInfo(Account);
            //載入user表中的資料到字典中
            for (int i = 0; i < tableOpeinfo.Rows.Count; i++)
            {
                dic.Add(Convert.ToString(tableOpeinfo.Rows[i]["userID"]), Convert.ToString(tableOpeinfo.Rows[i]["UserName"]));
                comboBox1.Items.Add(Convert.ToString(tableOpeinfo.Rows[i]["userID"]));
            }
        }
        #endregion

        
        #region tabControl1空件不同選項卡觸發不同的事件
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // Account.UserID= comboBox1.Text.Trim();
            Account.RechargeCash = 0;
            Account.CancelCash = 0;
            Account.ConsumeCash = 0;
            Account.AllCash = 0;
            Account.Date = "";



            #region  //觸發充值選項卡

            if (tabControl1.SelectedTab.Name == "tabCharge")
            {
                Account.count = 1;
                DataTable dtRecharge = FSettleAcount.selectInfo(Account);
                dtgRecharge.DataSource = dtRecharge;
                dtgRecharge.Columns["cardno"].HeaderText = "卡號";
                dtgRecharge.Columns["addmoney"].HeaderText = "充值金額";
                dtgRecharge.Columns["date"].HeaderText = "充值日期";
                dtgRecharge.Columns["time"].HeaderText = "充值時間";

                sumRecharge = 0;
                //求和
                if (dtRecharge.Rows.Count > 0)
                {
                    for (int i = 0; i < dtRecharge.Rows.Count; i++)
                    {
                        sumRecharge = Convert.ToInt32(dtRecharge.Rows[i]["addmoney"]) + sumRecharge;
                        Account.RechargeCash = sumRecharge;
                    }
                }
                dtgRecharge.AllowUserToAddRows = false;
            }
           
            #endregion


            //觸發退卡選項卡
            if (tabControl1.SelectedTab.Name == "tabCancelCard")
            {
                Account.count = 2;
                DataTable dtCancel = FSettleAcount.selectInfo(Account);
                dtgCancelCard.DataSource = dtCancel;

                dtgCancelCard.Columns["cardNo"].HeaderText = "卡號";
                dtgCancelCard.Columns["CancelCash"].HeaderText = "退還金額";
                dtgCancelCard.Columns["Date"].HeaderText = "退卡日期";
                dtgCancelCard.Columns["time"].HeaderText = "退卡時間";
                sumCancel = 0;

                if (dtCancel.Rows.Count > 0)
                {
                    for (int i = 0; i < dtCancel.Rows.Count; i++)
                    {
                        sumCancel = Convert.ToInt32(dtCancel.Rows[i]["CancelCash"]) + sumCancel;
                        Account.CancelCash = sumCancel;
                    }
                }
                dtgCancelCard.AllowUserToAddRows = false;
            }
            //觸發結賬選項卡
            if (tabControl1.SelectedTab.Name == "tabAllcash")
            {
                txtRechargeCash.Text = Convert.ToString(sumRecharge);
                txtCancelCash.Text = Convert.ToString(sumCancel);
                //計算consumecash
                DataTable tableConsumeCash = FSettleAcount.selectConsumeCash(Account);
                txtConsumeCash.Text = Convert.ToString(tableConsumeCash.Rows[0][0]);
            }

            //觸發退出選項卡
            if (tabControl1.SelectedTab.Name == "tabExit")
            {
                this.Close();
            }
        } 
        #endregion

        //點選使用者id下拉框,出現相應內容
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            Facade.SettleAountFacade FOpeInfo = new Facade.SettleAountFacade();
          
            Account.UserID = comboBox1.Text.Trim();
            //通過選中字典中鍵,對映到值
            string strvalue;
            if (dic.ContainsKey(comboBox1.Text.Trim()))
            {
                bool result = dic.TryGetValue(comboBox1.Text.Trim(), out strvalue);
                if (result == true)
                    txtUserName.Text = strvalue;
            }
            tabControl1.Enabled = true;
            btnOK.Enabled = true;
        }

        //結賬按鈕
        private void btnOK_Click(object sender, EventArgs e)
        {
            Account.count = 3;
            Account.Date = DateTime.Now.ToShortDateString();
            bool flagAccount = FSettleAcount.updateInfo(Account);
            if (flagAccount==true)
            {
                MessageBox.Show("結賬成功");
            }
            else
            {
                MessageBox.Show("已經結賬");
                btnOK.Enabled = false;
            }
        }

        private void tabAllcash_Click(object sender, EventArgs e)
        {

        }
    }