學生管理系統程式碼

iDotNetSpace發表於2009-07-13

XML



 
  
  
  
 

DBHelper 

namespace StudentManager
{
    public class DBHelper
    {
        ///


        /// 獲得連線字串,使用sql資料庫
        ///

        private static string constring ="server=.;uid=sa;database=StudentManager;pwd=";
        ///
        /// 執行增刪改操作
        ///

        /// 傳入增刪改的sql語句
        /// 返回受影響的行數
        public static int ExecuteNonQuery(string sql)
        {
            int i=0;
            using(SqlConnection con = new SqlConnection(constring))
            {
                using (SqlCommand cmd = new SqlCommand(sql,con))
                {
                    con.Open();
                    i= cmd.ExecuteNonQuery();
                    con.Close();
                }
            }
            return i;
        }
        ///
        /// 執行查詢操作
        ///

        /// 查詢語句
        /// 返回查詢結果
        public static SqlDataReader ExecuteReader(string sql)
        {
            SqlConnection con = new SqlConnection(constring);
            SqlCommand cmd = new SqlCommand(sql, con);
            cmd.Connection.Open();
            return cmd.ExecuteReader(CommandBehavior.CloseConnection);
        }
    }
}

工廠類

 public  class Factory
    {
        public static IStudent CreateStudentDAL()
        {
            IStudent idal = null;
            //從配置檔案中載入程式集的名稱
            string 程式集 = System.Configuration.ConfigurationManager.AppSettings["程式集"];            
            string 名稱空間 = System.Configuration.ConfigurationManager.AppSettings["名稱空間"];
            //從配置檔案中載入資料訪問層的名稱
            string 類 = System.Configuration.ConfigurationManager.AppSettings["類"];
            //通過反射建立資料訪問物件
            idal = (IStudent)Assembly.Load(程式集).CreateInstance(名稱空間+"."+類);
            return idal;
        }
    }

form1 

namespace StudentManager
{
    public partial class Form1 : Form
    {
       // bool Flag = false;//標誌位,表示使用者是否選擇過要修改或刪除的資料行。
        int id;
        //通過工廠建立物件
        IStudent studal = Factory.CreateStudentDAL();
        public Form1()
        {
            InitializeComponent();
        }
        ///


        /// 窗體載入時,顯示所有資訊
        ///

        ///
        ///
        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.ReadOnly = true;//不允許使用者修改行
            SE.SkinFile = Application.StartupPath + "\\skin\\OneGreen.ssk";          
            StudentView();
        }
        private void StudentView()
        {
            dataGridView1.DataSource = studal.GetAll();
        }
        //檢視學生資訊
        private void btnView_Click(object sender, EventArgs e)
        {
            StudentView();            
        }
        //新增學生資訊
        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (txtName.Text == "" || txtAge.Text == "")
            {
                MessageBox.Show("請將資訊填寫完整", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                return;
            }
            try
            {
                int.Parse(txtAge.Text);
            }
            catch
            {
                MessageBox.Show("年齡必須為整數","輸入錯誤",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return;
            }
            string name = txtName.Text;
            if (studal.SelectByUserName(name))
            {
                MessageBox.Show("該學生已存在,請與管理員聯絡","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information  );
                return;
            }              
            //新增學生方法1
            string gender = radMale.Checked ? radMale.Text : radFemale.Text;
            //父類引用指向子類,呼叫子類的方法
            int i = studal.AddStudent(txtName.Text, txtAge.Text, gender, dtpCreateDate.Value);
            
            //新增學生方法2
            //StudentModel studentModel = new StudentModel();
            //studentModel.Stuname = txtName.Text;
            //studentModel.Gender = radMale.Checked ? radMale.Text : radFemale.Text;
            //studentModel.CreateDate = dtpCreateDate.Value;
            //int i = studal.AddStudent(studentModel);
            if (i > 0)
            {
                MessageBox.Show("新增成功", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
               // btnView.PerformClick();
                StudentView();
            }
            else
            {
                MessageBox.Show("新增學生時產生了系統錯誤,請與管理員聯絡。", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
        }
        //判斷是否選中某行
        private void dataGridView1_Click(object sender, EventArgs e)
        {
            //整行選中
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
                //判斷是否選中某行
            if (dataGridView1.SelectedRows.Count > 0)
            {
                int id = dataGridView1.CurrentRow.Index;
                // int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
                txtName.Text = dataGridView1.SelectedRows[0].Cells["Column2"].Value.ToString();
                radMale.Checked = true;
                if (dataGridView1.SelectedRows[0].Cells["Column3"].Value.ToString() == "女")
                {
                    radFemale.Checked  = true; 
                }
                txtAge.Text = dataGridView1.SelectedRows[0].Cells["Column4"].Value.ToString();
                dtpCreateDate.Text = dataGridView1.SelectedRows[0].Cells["Column5"].Value.ToString();

            }
            else {
                MessageBox.Show("請先選中要更新的行","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information );
            }
        }
        //更新學生資訊
        private void btnUpdate_Click(object sender, EventArgs e)
        {  
            //獲取當前選中的索引
            id = int.Parse( dataGridView1.SelectedRows[0].Cells["Column1"].Value.ToString());
            string sex = radMale.Checked ? radMale.Text : radFemale.Text;
            try
            {
                int.Parse(txtAge.Text);
            }
            catch
            {
                MessageBox.Show("年齡必須為整數", "輸入錯誤", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            if (txtName.Text == "" || txtAge.Text  == "" || dtpCreateDate.Text == "")
            {
                MessageBox.Show("請輸入詳細的學生資訊","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information );
                return;
            }
            int i = studal.updateStudent(txtName.Text, txtAge.Text, sex, dtpCreateDate.Value, id);
            if (i > 0)
            {
                MessageBox.Show("更新成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                StudentView();
            }
            else
            {
                MessageBox.Show("更新失敗", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        //刪除學生資訊
        private void btnDelete_Click(object sender, EventArgs e)
        {
            //dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            //if(Flag ==false)
            //{
            //    MessageBox.Show("請選擇要刪除的行","提示",MessageBoxButtons .OK ,MessageBoxIcon.Warning  );
            //    return;
            //}
            if (MessageBox.Show("確實要刪除嗎?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.No)
            {  
                return;
            }
            id = int.Parse(dataGridView1.SelectedRows[0].Cells["Column1"].Value.ToString());           
            int i = studal.deleteStudent(id);
            if (i > 0)
            {
                MessageBox.Show("刪除成功", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                StudentView();
            }
            else
            {
                MessageBox.Show("刪除失敗", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        //序列化檢視
        private void button3_Click(object sender, EventArgs e)
        {
            dataGridView1.DataSource = userable.getUser();
        }       
      //序列化
        private void button1_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream("e:\\student.bat",FileMode .Create );
            BinaryFormatter bf = new BinaryFormatter();
            DataTable dt = (DataTable)dataGridView1.DataSource;
            bf.Serialize(fs,dt);
            dataGridView1.DataSource = null;
            fs.Close();
            fs.Dispose();
            MessageBox.Show("已將資料序列化"); 
        }
      //反序列化
        private void button2_Click(object sender, EventArgs e)
        {
            FileStream fs = new FileStream("e:\\student.bat",FileMode .Open );
            BinaryFormatter bf = new BinaryFormatter();
            DataTable dt = bf.Deserialize(fs) as DataTable;
            fs.Close();
            fs.Close();
            MessageBox.Show("反序列化成功");
        }         
    }

DAL

namespace StudentManager
{
    ///


    /// 具體產品,連線到sql資料庫
    ///

    public class SqlStudentDAL :IStudent
    {
        ///
        /// 查詢所有資訊
        ///

        /// 泛型集合
        public List GetAll()
        {
            string sql = "select * from Student";
            List list = new List();
            SqlDataReader reader = DBHelper.ExecuteReader(sql);
            while(reader.Read())
            {
                StudentModel stuModel = new StudentModel();
                stuModel.Id = reader["id"].ToString();
                stuModel.Stuname = reader["stuname"].ToString();
                stuModel.Gender = reader["Gender"].ToString();
                stuModel.Age = reader["Age"].ToString();
                stuModel.CreateDate = DateTime.Parse(reader["CreateDate"].ToString());
                list.Add(stuModel);
            }
            reader.Close();
            return list;
        }
        ///
        /// 新增學生
        ///

        /// 傳入學生類
        /// 返回影響的行數
        public int AddStudent(StudentModel studentModel) 
        {
            string sql =string.Format( "insert into Student values('{0}','{1}',{2},'{3}')",studentModel.Stuname,studentModel.Gender,studentModel.Age,studentModel.CreateDate);
            return DBHelper.ExecuteNonQuery(sql);
        }
       ///
       /// 新增學生---------方法過載
       ///

       /// 姓名
       /// 年齡
       /// 性別
       /// 日前
        /// 返回影響的行數
        public int AddStudent(string name, string age, string gender, DateTime crreateDate) 
        {
            string sql = string.Format("insert into Student values('{0}','{1}',{2},'{3}')", name, gender, age, crreateDate);
            return DBHelper.ExecuteNonQuery(sql);
        }
        ///
        /// 根據使用者名稱查詢使用者
        ///

        /// 使用者名稱
        ///
        public bool SelectByUserName(string name)
        {
            string sql = string .Format ("select * from Student where stuname='{0}'",name);
            SqlDataReader reader = DBHelper .ExecuteReader (sql);
            return reader.HasRows;
        }
        ///
        /// 更新學生---------方法過載S
        ///

        /// 學生物件
        /// 返回受影響的行數
        public int updateStudent(StudentModel studentModel)
        {
            string sql = string.Format("update Student set stuname='{0}',Gender='{1}',Age='{2}',CreateDate='{3}' where id='{4}'", studentModel.Stuname, studentModel.Gender, studentModel.Age, studentModel.CreateDate, studentModel.Id);
            return DBHelper.ExecuteNonQuery(sql);
        }
        public int updateStudent(string name, string age, string gender, DateTime crreateDate, int id)
        {
            string sql = string.Format("update Student set stuname='{0}',Age='{1}',Gender='{2}',CreateDate='{3}' where id='{4}'", name, age, gender, crreateDate, id);
            return DBHelper.ExecuteNonQuery(sql);
        }
        ///
        /// 執行刪除操作
        ///

        /// 要刪除的行號
        ///
        public int deleteStudent(int id)
        {
            string sql = string.Format("delete from Student where id='{0}'",id );
            return DBHelper.ExecuteNonQuery(sql);
        }
        
    }
}


 

 namespace StudentManager
{
    ///


    /// 抽象產品
    ///

    public interface IStudent
    {
        List GetAll();
        //增加學生
        int AddStudent(StudentModel studentModel);
        int AddStudent( string name, string age, string gender, DateTime crreateDate);
        //根據學生姓名查詢使用者資訊
        bool SelectByUserName(string name);
        //更新學生資訊
        int updateStudent(StudentModel studentModel);
        int updateStudent(string name, string age, string sex, DateTime crreateDate, int id);
        //刪除學生
        int deleteStudent(int id);
    }
}

 

建立序列化

namespace StudentManager
{
    [Serializable]
    public class userable
    {
        public static DataTable getUser()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("id");
            dt.Columns.Add("stuname");
            dt.Columns.Add("Gender");
            dt.Columns.Add("Age");
            dt.Columns.Add("CreateDate");
            DataRow row = dt.NewRow ();
            row[0]=1;
            row[1]="cn129";
            row[2]="男";
            row[3]=20;
            row[4] = "2009-6-8";
            dt.Rows.Add(row);

            row = dt.NewRow();
            row[0] = 2;
            row[1] = "cn123";
            row[2] = "男";
            row[3] = 23;
            row[4] = "2009-6-8";
            dt.Rows.Add(row);
            return dt;
        }
    }
}

namespace StudentManager

 

    //實體類,這個類的每一個物件,表示資料庫中的一條記錄,即一個學生
    public class StudentModel
    {
        //封裝欄位
        //學號
        private string _id;
        public string Id
        {
            get { return _id; }
            set { _id = value; }
        }

        //姓名
        private string _stuname;
        public string Stuname
        {
            get { return _stuname; }
            set { _stuname = value; }
        }

        //性別
        private string _Gender;
        public string Gender
        {
            get { return _Gender; }
            set { _Gender = value; }
        }

        //年齡
        private string _Age;
        public string Age
        {
            get { return _Age; }
            set
            {
                _Age = value;
            }
        }

        //入學時間
        private DateTime _CreateDate;
        public DateTime CreateDate
        {
            get { return _CreateDate; }
            set { _CreateDate = value; }
        }

        ///


        /// 建構函式
        ///

        public StudentModel() { }
        public StudentModel(string id,string stuname,string gender,string age,DateTime createDate) 
        {
            this._id = id;
            this._stuname = stuname;
            this._Gender = gender;
            this._Age = age;
            this._CreateDate = createDate;
        }
    }
}

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-608972/,如需轉載,請註明出處,否則將追究法律責任。

相關文章