2.C#实验五:ADO.NET数据库操作练习详解

  周六忙了一下午,终于把C#实验五(扩充实验):ADO.NET数据库操作练习给严格按照老师的要求给解决了,下面分享一下主要思路和代码,望同学们别笑,这个实验是ADO.NET中最基本的对数据库增删改查操作,数据访问和业务逻辑全部用代码完成,不带一点数据库绑定控件。由于写得很仓促,没有优化,里面还有很多不尽人意的地方。

    注意:项目建好后需要在引用中添加System.Configuration的引用,并按实验要求建好数据库就行!
    项目整体树形结构图:

    登陆页面Name注释:

 

    主窗体Name注释:

 

 

 

    程序入口代码:文件名Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace ADO
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            string dataDir = AppDomain.CurrentDomain.BaseDirectory;
            if (dataDir.EndsWith(@"\bin\Release\") || dataDir.EndsWith(@"\bin\Debug\"))
            {
                dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
                AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
            }
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormLogin());
        }
    }
}

    应用程序配置文件信息:文件名App.config

 <?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <connectionStrings>
    <add name="ShiYanFive" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\App_Data\Student.mdf;Integrated Security=True"/>
  </connectionStrings>
</configuration>

     数据访问层代码:文件名DatabaseOperation.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;

namespace ADO.App_Code.DAL
{
    public static class DatabaseOperation
    {
        //静态只读变量,用来存取数据库连接字符串
        private static readonly string constr = ConfigurationManager.ConnectionStrings["ShiYanFive"].ConnectionString;
       
        /// <summary>
        /// 用来执行带参数和不带参数仅返回所影响的行数的sql语句,如:insert,delete,update
        /// </summary>
        /// <param name="sql">所要执行的sql语句</param>
        /// <param name="pams">sql语句中所带的参数</param>
        /// <returns>返回所影响的行数</returns>
        public static int ExecuteNonQuery(string sql, params SqlParameter[] pams)
        {
            using (SqlConnection conn = new SqlConnection(constr))
            {
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    if (pams!=null)
                    {
                        cmd.Parameters.AddRange(pams);
                    }
                    if (conn.State == ConnectionState.Closed)
                    {
                        conn.Open();
                    }
                    return cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// 返回一个DataTable,可以执行select语句
        /// </summary>
        /// <param name="sql">所要执行的sql语句</param>
        /// <param name="pams">sql语句中所带的参数</param>
        /// <returns>返回一个DataTable</returns>
        public static DataTable ExecuteDataTable(string sql, params SqlParameter[] pams)
        {
            using(SqlDataAdapter adapter=new SqlDataAdapter(sql,constr))
            {
                if(pams!=null)
                {
                    adapter.SelectCommand.Parameters.AddRange(pams);
                }
                DataTable dt=new DataTable();
                adapter.Fill(dt);
                return dt;
            }
        }
    }
}

    业务逻辑层代码1:文件名Login.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using ADO.App_Code.DAL;
using System.Data;

namespace ADO.App_Code.BLL
{
    class Login
    {
        public static int LoginForm(string username, string password)
        {
            string sql = "select * from Manager where username=@username and password=@password";
            SqlParameter[] pams ={
                                    new SqlParameter("@username",username),
                                    new SqlParameter("@password",password)
                                };
            DataTable dt = DatabaseOperation.ExecuteDataTable(sql, pams);
            return dt.Rows.Count;
        }
    }
}
    业务逻辑层代码2:StudentOperation.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ADO.App_Code.DAL;
using System.Data.SqlClient;

namespace ADO.App_Code.BLL
{
    public static class StudentOperation
    {
        /// <summary>
        /// 查询Student表中的所有数据
        /// </summary>
        /// <returns>返回的是一个DataTable表</returns>
        public static DataTable getStudentDataTable()
        {
            DataTable dt = new DataTable();
            string sql="select * from Student";
            dt = DatabaseOperation.ExecuteDataTable(sql);
            return dt;
        }

        /// <summary>
        /// 按姓名和性别条件查询Student表中的数据
        /// </summary>
        /// <param name="name">姓名</param>
        /// <param name="sex">性别</param>
        /// <returns>返回按姓名和性别条件查询的DataTable表</returns>
        public static DataTable getStudentDataTable(string name, string sex)
        {
            string sql = "select * from Student where
studentName=@studentName and sex=@sex";
            DataTable dt = new DataTable();
            dt = DatabaseOperation.ExecuteDataTable(sql, new SqlParameter("@studentName", name), new SqlParameter("@sex", sex));
            return dt;
        }

        /// <summary>
        /// 按学号条件查询Student表中的数据
        /// </summary>
        /// <param name="studentNO">学号</param>
        /// <returns>返回按学号条条件查询的DataTable表</returns>
        public static DataTable getStudentDataTable(string studentNO)
        {
            string sql = "select * from Student where
StudentNO=@StudentNO";
            DataTable dt = new DataTable();
            dt = DatabaseOperation.ExecuteDataTable(sql, new SqlParameter("@StudentNO", studentNO));
            return dt;
        }

        /// <summary>
        /// 向Student表中插入数据
        /// </summary>
        /// <param name="studentNO">学号</param>
        /// <param name="name">姓名</param>
        /// <param name="sex">性别</param>
        /// <param name="datetime">出生日期</param>
        /// <param name="department">学院</param>
        /// <returns>返回插入数据后所影响的行数</returns>
        public static int insertStudent(string studentNO, string name, string sex, DateTime datetime, string department)
        {
            string sql = "insert into Student values(@StudentNO,@studentname,@sex,@birthday,@department)";
            SqlParameter[] pams ={
                                    new SqlParameter("@StudentNO",studentNO),
                                    new SqlParameter("@studentname",name),
                                    new SqlParameter("@sex",sex),
                                    new SqlParameter("@birthday",datetime),
                                    new SqlParameter("@department",department)
                                };
            return DatabaseOperation.ExecuteNonQuery(sql, pams);
        }

        /// <summary>
        /// 按学号对Student表进行更新
        /// </summary>
        /// <param name="studentNO">学号</param>
        /// <param name="name">姓名</param>
        /// <param name="sex">性别</param>
        /// <param name="datetime">生日</param>
        /// <param name="department">学院</param>
        /// <returns>返回更新后缩影响的行数</returns>
        public static int updateStudent(string studentNO, string name, string sex, DateTime datetime, string department)
        {
            string sql = "update Student set
studentName=@studentName,sex=@sex,birthday=@birthday,department=@department where StudentNO=@studentNO";
            SqlParameter[] pams ={
                                    new SqlParameter("@studentName",name),
                                    new SqlParameter("@sex",sex),
                                    new SqlParameter("@birthday",datetime),
                                    new SqlParameter("@department",department),
                                    new SqlParameter("@studentNO",studentNO),
                                };
            return DatabaseOperation.ExecuteNonQuery(sql, pams);
        }

        /// <summary>
     /// 按学号删除Student表中的信息
        /// </summary>
        /// <param name="studentNO">学号</param>
        /// <returns>返回删除后所影响的行数</returns>
        public static int deleteStudent(string studentNO)
        {
            string sql = "delete from Student where
StudentNO=@StudentNO";
            return DatabaseOperation.ExecuteNonQuery(sql, new SqlParameter("@StudentNO", studentNO));
        }
    }
}

    登录窗体后台代码:文件名LoginForm.cs

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ADO.App_Code.BLL;
using ADO.UI;

namespace ADO
{
    public partial class FormLogin : Form
    {
        public FormLogin()
        {
            InitializeComponent();
        }

        //确定按钮事件

        private void buttonQueding_Click(object sender, EventArgs e)
        {
            if (textBoxUserName.Text != "" && textBoxPassword.Text != "")
            {
                if (Login.LoginForm(textBoxUserName.Text, textBoxPassword.Text) > 0)
                {
                    //MessageBox.Show("登陆成功!");
                    MainForm mainForm = new MainForm();
                    mainForm.Show();
                    this.Hide();
                }
                else
                {
                    MessageBox.Show("用户名和密码错误,请重新输入。");
                    textBoxUserName.Text = "";
                    textBoxPassword.Text = "";
                }
            }
            else
            {
                MessageBox.Show("用户名和密码不能为空,请重新输入。");
                textBoxUserName.Text = "";
                textBoxPassword.Text = "";
            }
        }

        //取消按钮事件

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

    主窗体后台代码:文件名MainForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ADO.App_Code.BLL;

namespace ADO.UI
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        public DataGridView DataGridViewDetails//定义dataGridViewDetails的公有属性,方便在事件函数外操作以及对dataGridViewDetails的操作方法的封装
        {
            get
            {
                return this.dataGridViewDetails;//返回私有字段dataGridViewDetails
            }
        }

        //加载窗体时的事件

        private void MainForm_Load(object sender, EventArgs e)
        {
            //调用getStudentTable()方法,获取Student表中的全部数据,并绑定到DataGridViewDetails
            getStudentTable();

            //向comboBoxSex中添加数据项集合,并设置索引为0的项为默认显示项
            comboBoxSex.Items.Add("男");
            comboBoxSex.Items.Add("女");
            comboBoxSex.SelectedIndex = 0;

            //设定单选按钮的“男”属性为默认选定
            radioButtonSex1.Checked = true;
        }

        //查询按钮事件

        private void buttonSelect_Click(object sender, EventArgs e)
        {
            //调用getStudentTable(string name, string sex)方法,按姓名和性别条件获取Student表中的数据信息,并绑定到DataGridViewDetails
            getStudentTable(textBoxName.Text, comboBoxSex.SelectedItem.ToString());
        }

        //增加按钮事件

        private void buttonInsert_Click(object sender, EventArgs e)
        {
            string studentNO = textBoxNO.Text;//获取学号
            string name = textBoxName2.Text;//获取姓名
            string sex;//获取性别
            if (radioButtonSex1.Checked)
            {
                sex = radioButtonSex1.Text;
            }
            else
            {
                sex = radioButtonSex2.Text;
            }
            DateTime datetime = dateTimePicker1.Value;//获取出生日期
            string department = textBoxDepartment.Text;//获取学院

            //插入数据前查询数据库学号是否相同,因为学号是数据库Student表的主键,如果相同,则无法插入
            int rows = StudentOperation.getStudentDataTable(studentNO).Rows.Count;
            if (rows > 0)
            {
                MessageBox.Show("不能插入相同的学号信息!");
            }
            else
            {
                int row = StudentOperation.insertStudent(studentNO, name, sex, datetime, department);
                if (row > 0)
                {
                    MessageBox.Show("插入成功!");
                    getStudentTable();
                }
                else
                {
                    MessageBox.Show("数据库操作失败!");
                }
            }
        }

        //修改按钮事件

        private void buttonUpdate_Click(object sender, EventArgs e)
        {
            string studentNO = textBoxNO.Text;//获取学号
            string name = textBoxName2.Text;//获取姓名
            string sex;//获取性别
            if (radioButtonSex1.Checked)
            {
                sex = radioButtonSex1.Text;
            }
            else
            {
                sex = radioButtonSex2.Text;
            }
            DateTime datetime = dateTimePicker1.Value;//获取出生日期
            string department = textBoxDepartment.Text;//获取学院

            if (StudentOperation.updateStudent(studentNO, name, sex, datetime, department) > 0)
            {
                MessageBox.Show("更新成功!");
                getStudentTable();
            }
            else
            {
                MessageBox.Show("更新失败!");
            }

        }

        //删除按钮事件

        private void buttonDelete_Click(object sender, EventArgs e)
        {
            string studentNO = textBoxNO.Text;//获取学号
            if (StudentOperation.deleteStudent(studentNO) > 0)
            {
                MessageBox.Show("删除成功!");
                getStudentTable();
            }
            else
            {
                MessageBox.Show("删除失败!");
            }
        }

        //dataGridView点击事件

        private void dataGridViewDetails_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = dataGridViewDetails.CurrentRow;//获取当前点击行的信息
           
            //以下是获取当前点击行的每一列的数据信息
            string studentNO = row.Cells[0].Value.ToString();
            string name = row.Cells[1].Value.ToString();
            string sex = row.Cells[2].Value.ToString();
            DateTime datetime = Convert.ToDateTime(row.Cells[3].Value);
            string department = row.Cells[4].Value.ToString();
           
            //以下是分别把获取到的值赋值主窗体下面的每一个文本框
            textBoxNO.Text = studentNO;
            textBoxName2.Text = name;
            if (sex=="男")
            {
                radioButtonSex1.Checked = true;
            }
            else if (sex == "女")
            {
                radioButtonSex2.Checked = true;
            }
            dateTimePicker1.Value = datetime;
            textBoxDepartment.Text = department;
        }

        //当主窗体关闭时的事件

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //当点击主窗体右上角的退出按钮时,整个程序全部退出
            Application.Exit();
        }

        /// <summary>
        /// 获取Student表中的全部数据,并绑定到DataGridViewDetails
        /// </summary>
        private void getStudentTable()
        {
            //先清除DataGridView中的原有数据
            for (int i = 0; i < DataGridViewDetails.Rows.Count; i++)
            {
                DataGridViewDetails.Rows.Remove(DataGridViewDetails.Rows[i]);
            }

            //调用StudentOperation.getStudentDataTable()方法返回一个装有Student表全部信息的DataTable,然后绑定到DataGridView的数据源
            DataGridViewDetails.DataSource = StudentOperation.getStudentDataTable();

            //调用setDataGridViewColumnsTitle()方法设定DataGridView的每一列的标题名
            setDataGridViewColumnsTitle();

            //取消DataGridView的默认选中行
            DataGridViewDetails.Rows[0].Selected = false;
        }

        /// <summary>
        /// 按姓名和性别条件获取Student表中的数据信息,并绑定到DataGridViewDetails
        /// </summary>
        /// <param name="name">姓名</param>
        /// <param name="sex">性别</param>
        private void getStudentTable(string name, string sex)
        {
            //先清除DataGridView中的原有数据
            for (int i = 0; i < DataGridViewDetails.Rows.Count; i++)
            {
                DataGridViewDetails.Rows.Remove(DataGridViewDetails.Rows[i]);
            }

            //调用StudentOperation.getStudentDataTable(name, sex)返回一个按姓名和性别查询的Student表
            DataTable dt=StudentOperation.getStudentDataTable(name, sex);
           
            //判断返回的表的行数,如果大于0,则把该表绑定到DataGridView的数据源
            if (dt.Rows.Count > 0)
            {
                DataGridViewDetails.DataSource = dt;
                setDataGridViewColumnsTitle();
            }

            //取消DataGridView的默认选中行
            DataGridViewDetails.Rows[0].Selected = false;
        }

        /// <summary>
        /// 设置DataGridView中列的标题
        /// </summary>
        private void setDataGridViewColumnsTitle()
        {
            DataGridViewDetails.Columns["StudentNO"].HeaderText = "学号";
            DataGridViewDetails.Columns["studentName"].HeaderText = "姓名";
            DataGridViewDetails.Columns["sex"].HeaderText = "性别";
            DataGridViewDetails.Columns["birthday"].HeaderText = "出生日期";
            DataGridViewDetails.Columns["department"].HeaderText = "学院";

            //以下方式也可行
            //DataGridViewDetails.Columns[0].HeaderText = "学号";
            //DataGridViewDetails.Columns[1].HeaderText = "姓名";
            //DataGridViewDetails.Columns[2].HeaderText = "性别";
            //DataGridViewDetails.Columns[3].HeaderText = "出生日期";
            //DataGridViewDetails.Columns[4].HeaderText = "学院";
        }
    }
}

posted on 2011-11-24 12:17  Barclay.Xu  阅读(3114)  评论(3编辑  收藏  举报