通过一个完整的实例实现课程信息管理功能的操作,包括查询、修改、删除课程信息等操作。

1) 创建课程信息表

create table StuCourse
(
id int primary key identity(1,1),
name varchar(20),
credit numeric(3,1),
remark varchar(50)
);

  INSERT INTO StuCourse (name,credit,remark) VALUES ('English',3.00,'Good Good Study');
  INSERT INTO StuCourse (name,credit,remark) VALUES ('Math',2.56,'Good Good Study, Day');
  INSERT INTO StuCourse (name,credit,remark) VALUES ('Chinese',4.04,'Good Good Study, Day Day');
  INSERT INTO StuCourse (name,credit,remark) VALUES ('English1',3.00,'Good Good Study');
  INSERT INTO StuCourse (name,credit,remark) VALUES ('Math1',2.56,'Good Good Study, Day');
  INSERT INTO StuCourse (name,credit,remark) VALUES ('Chinese1',4.04,'Good Good Study, Day Day');

2) 课程信息管理界面的设计

  DataGridView 控件用于显示课程信息,并提供了根据课程名称查找课程信息、修改以及删除的功能,另外提供增加课程功能(暂无)。

  

   

3) 具体代码

  实体类:

  /// <summary>
  /// 课程实体类(实际应创建一实体类的项目,里面可能有多个实体类)
  /// </summary>
  public class Entities
  {
    /// <summary>
    /// 编号(数据库中的自增主键)
    /// </summary>
    public int ID { get; set; }
    /// <summary>
    /// 课程名称
    /// </summary>
    public string Name { get; set; }
    /// <summary>
    /// 课程学分
    /// </summary>
    public float Credit { get; set; }
    /// <summary>
    /// 备注
    /// </summary>
    public string Remark { get; set; }
  }

  业务层数据层:

  /// <summary>
  /// 课程相关处理类(实际应将业务逻辑层BLL与数据库层DAL分开,各自创建一个项目)
  /// </summary>
  public class CourseInfo
  {
    static string conString = "Data Source=.;Initial Catalog=TestDB;Integrated Security=True;";

    /// <summary>
    /// 返回所有课程信息
    /// </summary>
    /// <returns> List<Entities></returns>
    public static List<Entities> GetAllCourseInfo()
    {
      SqlDataReader reader = null;
      try
      {
        List<Entities> entities = new List<Entities>();
        string sqlStr = "SELECT * FROM StuCourse";
        using (SqlConnection con = new SqlConnection(conString))
        {
          con.Open();
          SqlCommand cmd = new SqlCommand(sqlStr, con);
          reader = cmd.ExecuteReader();
          while (reader.Read())
          {
            int id = reader["id"] == DBNull.Value ? -1 : Convert.ToInt32(reader["id"]);
            string name = reader["name"] == DBNull.Value ? "" : reader["name"].ToString();
            float credit = reader["credit"] == DBNull.Value ? 0f : Convert.ToSingle(reader["credit"]);
            string remark = reader["remark"] == DBNull.Value ? "" : reader["remark"].ToString();

            Entities entity = new Entities()
            {
              ID = id,
              Name = name,
              Credit = credit,
              Remark = remark
            };
            entities.Add(entity);
          }
        }
        return entities;
      }
      catch (Exception)
      {
        //打印log
        throw;
      }
      finally
      {
        if (reader != null)
        {
          reader.Close();
        }
      }
    }

/// <summary>
/// 返回查找的课程信息,模糊查询
/// </summary>
/// <param name="courseName"></param>
/// <returns>List<Entities></returns>
public static List<Entities> GetTheCourseInfo(string courseName)
{
  SqlDataReader reader = null;
  try
  {
    string sqlStr = "";
    List <Entities> entities = new List<Entities>();
    if (courseName == "All Course")
      sqlStr = $"SELECT * FROM StuCourse";
    else
      sqlStr = $"SELECT * FROM StuCourse WHERE name like '%{courseName}%'";
    using (SqlConnection con = new SqlConnection(conString))
    {
      con.Open();
      SqlCommand cmd = new SqlCommand(sqlStr, con);
      reader = cmd.ExecuteReader();
      while (reader.Read())
      {
        int id = reader["id"] == DBNull.Value ? -1 : Convert.ToInt32(reader["id"]);
        string name = reader["name"] == DBNull.Value ? "" : reader["name"].ToString();
        float credit = reader["credit"] == DBNull.Value ? 0f : Convert.ToSingle(reader["credit"]);
        string remark = reader["remark"] == DBNull.Value ? "" : reader["remark"].ToString();

        Entities entity = new Entities()
        {
          ID = id,
          Name = name,
          Credit = credit,
          Remark = remark
        };
        entities.Add(entity);
      }
    }
    return entities;
  }
  catch (Exception)
  {
    //打印log
    throw;
  }
  finally
  {
    if (reader != null)
    {
      reader.Close();
    }
  }
}

/// <summary>
/// 删除
/// </summary>
/// <param name="courseID"></param>
/// <returns>int</returns>
public static int DeleteTheCourseInfo(int courseID)
{
  try
  {
    int res = -1;
    List<Entities> entities = new List<Entities>();
    string sqlStr = $"DELETE FROM StuCourse WHERE id = {courseID}";
    using (SqlConnection con = new SqlConnection(conString))
    {
      con.Open();
      SqlCommand cmd = new SqlCommand(sqlStr, con);
      res = cmd.ExecuteNonQuery();
    }

        return res;
      }  
      catch (Exception)
      {
        //打印log
        throw;
      }
    }

/// <summary>
/// 更新
/// </summary>
/// <param name="entity"></param>
/// <returns>int</returns>
public static int UpdateTheCourseInfo(Entities entity)
{
  try
  {
    int res = -1;
    string sqlStr = $@"UPDATE StuCourse SET name = N'{entity.Name}',
    credit = {entity.Credit}, remark = N'{entity.Remark}' WHERE id = {entity.ID}";
    using (SqlConnection con = new SqlConnection(conString))
    {
      con.Open();
      SqlCommand cmd = new SqlCommand(sqlStr, con);
      res = cmd.ExecuteNonQuery();
    }

        return res;
      }
      catch (Exception)
      {
        //打印log
        throw;
      }
    }

/// <summary>
/// 增加
/// </summary>
/// <param name="entity"></param>
/// <returns>int</returns>
public static int AddTheCourseInfo(Entities entity)
{
  try
  {
    int res = -1;
    string sqlStr = $@"INSERT INTO StuCourse (name,credit,remark) VALUES
    ('{entity.Name}', {entity.Credit}, '{entity.Remark}')";
    using (SqlConnection con = new SqlConnection(conString))
    {
      con.Open();
      SqlCommand cmd = new SqlCommand(sqlStr, con);
      res = cmd.ExecuteNonQuery();
    }

        return res;
      }
      catch (Exception)
      {
        //打印log
        throw;
      }
    }

  }

  界面代码:

public partial class Form1 : Form
{
  public Form1()
  {
    InitializeComponent();
  }

private void Form1_Load(object sender, EventArgs e)
{
  Init();
}

private void Init()
{
  List<Entities> allCourseInfo = CourseInfo.GetAllCourseInfo();
  dgvCourseInfo.DataSource = allCourseInfo;
  cbCourseName.Items.Add("All Course");
  for (int i = 0; i < allCourseInfo.Count; i++)
  {
    cbCourseName.Items.Add(allCourseInfo[i].Name);
  }
  if (cbCourseName.Items.Count > 0)
  {
    cbCourseName.SelectedIndex = 0;
  }
  //dgvCourseInfo.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

      //dgvCourseInfo.Columns[0].HeaderText = "id";
      //dgvCourseInfo.Columns[1].HeaderText = "名称";
    }

//private void cbCourseName_SelectedIndexChanged(object sender, EventArgs e)
//{
  // if (!string.IsNullOrWhiteSpace(cbCourseName.SelectedItem.ToString()))
  // {
    // btnSearch_Click(sender, e);
  // }
//}

//查询
private void btnSearch_Click(object sender, EventArgs e)
{
  List<Entities> theCourseInfo = CourseInfo.GetTheCourseInfo(cbCourseName.SelectedItem.ToString().Trim());
  if (theCourseInfo.Count > 0)
  {
    dgvCourseInfo.DataSource = null;
    dgvCourseInfo.DataSource = theCourseInfo;
    MessageBox.Show(theCourseInfo.Count.ToString() + "条数据", "Tips", MessageBoxButtons.OK,               MessageBoxIcon.Information);
  }
  else
  {
    dgvCourseInfo.DataSource = null;
    MessageBox.Show("No Data","Tips", MessageBoxButtons.OK,MessageBoxIcon.Information);
  }
}

//删除
private void btnDelete_Click(object sender, EventArgs e)
{
  if (dgvCourseInfo.DataSource == null)
  {
    MessageBox.Show("Search first", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
    return;
  }
  dgvCourseInfo.MultiSelect = false;
  DataGridViewSelectedRowCollection src = dgvCourseInfo.SelectedRows;
  if (src.Count == 0)
  {
    MessageBox.Show("Choose first", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
    return;
  }
  int id = Convert.ToInt32(src[0].Cells[0].Value);
  int res = CourseInfo.DeleteTheCourseInfo(id);

      if (res > 0)
      {
        List<Entities> allCourseInfo = CourseInfo.GetAllCourseInfo();
        dgvCourseInfo.DataSource = allCourseInfo;
      }
      else
      {
        MessageBox.Show("Delete failed", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return;
      }
    }

//更新
private void btnUpdate_Click(object sender, EventArgs e)
{
  if (dgvCourseInfo.DataSource == null)
  {
    MessageBox.Show("Search first", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
    return;
  }
  dgvCourseInfo.MultiSelect = false;
  DataGridViewSelectedRowCollection src = dgvCourseInfo.SelectedRows;
  if (src.Count == 0)
  {
    MessageBox.Show("Choose first", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
    return;
  }
  int id = Convert.ToInt32(src[0].Cells[0].Value);
  string name = src[0].Cells[1].Value.ToString();
  float credit = Convert.ToSingle(src[0].Cells[2].Value);
  string remark = src[0].Cells[3].Value.ToString();
  int res = CourseInfo.UpdateTheCourseInfo(new Entities() {
    ID=id,
    Name=name,
    Credit=credit,
    Remark=remark
  });

      if (res > 0)
      {
        List<Entities> allCourseInfo = CourseInfo.GetAllCourseInfo();
        dgvCourseInfo.DataSource = allCourseInfo;
      }
      else
      {
        MessageBox.Show("Update failed", "Tips", MessageBoxButtons.OK, MessageBoxIcon.Information);
        return;
      }
    }

  }

  不合理的地方有待改进。

  参考:http://c.biancheng.net/view/3040.html

ADO.NET 七(一个例子)的更多相关文章

  1. 用thinkphp写的一个例子:抓取网站的内容并且保存到本地

    我需要写这么一个例子,到电子课本网下载一本电子书. 电子课本网的电子书,是把书的每一页当成一个图片,然后一本书就是有很多张图片,我需要批量的进行下载图片操作. 下面是代码部分: public func ...

  2. 《The art of software testing》的一个例子

    这几天一直在看一本书,<The art of software testing>,里面有一个例子挺有感触地,写出来和大家分享一下: [问题] 从输入对话框中读取三个整数值,这三个整数值代表 ...

  3. spring笔记--使用springAPI以及自定义类 实现AOP的一个例子

    Spring的另一个重要思想是AOP,面向切面的编程,它提供了一种机制,可以在执行业务前后执行另外的代码,Servlet中的Filter就是一种AOP思想的体现,下面通过一个例子来感受一下. 假设我们 ...

  4. ReCap 360 photo照片建模技术的又一个例子

    这是我做的又一个利用Autodesk ReCap 360 照片建模技术做的一个例子.你可以下载模型自己把玩,或者下载原始照片自己试一试. 拍摄工具: 小米手机 照片数量:约120张 后期处理工具: p ...

  5. 从一个例子中体会React的基本面

    [起初的准备工作] npm init npm install --save react react-dom npm install --save-dev html-webpack-plugin web ...

  6. Erlang 程序引发共享内存 bug 的一个例子

    虽然 Erlang 的广告说得非常好,functional.share-nothing.消息传递,blah blah 的,好像用 Erlang 写并发程序就高枕无忧了,但是由于 Erlang 信奉高度 ...

  7. 对Jena的简单理解和一个例子

    本文简单介绍Jena(Jena 2.4),使用Protégé 3.1(不是最新版本)创建一个简单的生物(Creature)本体,然后参照Jena文档中的一个例子对本体进行简单的处理,输出本体中的Cla ...

  8. 使用flume的一个例子

    新项目中需要使用到hadoop和vertica,使用flume把数据加载到hadoop中,我做了一个例子, 即监控一个sharefolder,如果里面有文件,则会文件load到hadoop. 开启Fl ...

  9. php部分--面向对象三大特性-封装(另加连续调用的一个例子)、继承(重写、重载的例子)、多态;

    一.封装性: 目的:为了使类更加安全. 做法:1设置私有成员 2在类中建方法,访问私有成员 3在方法里边加控制(if) 私有成员访问的两种方法: 方法一:set(可写) get(可读)做方法(可读可写 ...

  10. Spark小课堂Week7 从Spark中一个例子看面向对象设计

    Spark小课堂Week7 从Spark中一个例子看面向对象设计 今天我们讨论了个问题,来设计一个Spark中的常用功能. 功能描述:数据源是一切处理的源头,这次要实现下加载数据源的方法load() ...

随机推荐

  1. 「ZJOI2019」开关

    传送门 Description 有一些一开始全都是关的开关,每次随机选择一个(每个开关概率不同)开关并改变它的状态,问达到目标状态的期望步数 Solution  \(P=\sum_{i=1}^{n}p ...

  2. centos7最小化安装准备工作

    1.配置网络 [root@localhost ~]# vim /etc/sysconfig/network-scripts/ifcfg-eno16780032 HWADDR=00:0C:29:48:9 ...

  3. Centos分区/超过2T的磁盘

    centos分区大于2TB 用parted分区工具分区 fdisk -l  查看要分的区(我这里是/dev/vdb) parted /dev/vdb    #进入/dev/vdb进行分区 mktabl ...

  4. springboot带有进度条的上传

    一.说明 最近要做文件上传,在网上找了很久都没有一个全面的示例,特此记录下来分享给大家. 1.文件上传接口可按照springboot默认实现,也可用commons-fileupload组件,本示例使用 ...

  5. spring boot validation参数校验

    对于任何一个应用而言在客户端做的数据有效性验证都不是安全有效的,这时候就要求我们在开发的时候在服务端也对数据的有效性进行验证. Spring Boot自身对数据在服务端的校验有一个比较好的支持,它能将 ...

  6. Ubuntu18.04启动memtest86

    对于Ubuntu18.04, 网上搜的结果都是错的, 根本不是启动时按shift, 而是按F8. 反复重启十几次后终于误触调出了启动菜单. 使用的是USB安装盘, 并且使用的是非UFEI模式.

  7. [转]小D课堂 - 零基础入门SpringBoot2.X到实战_汇总

    原文地址:https://www.cnblogs.com/wangjunwei/p/11392825.html 第1节零基础快速入门SpringBoot2.0 小D课堂 - 零基础入门SpringBo ...

  8. Laya的Tween缓动没有初始化repeat导致的Bug

    当你使用一个Tween给一个图标做旋转动画,循环播放.(repeat是播放次数, repeat=0无限循环,repeat=1播放一次) Laya.Tween.to(this.light,{rotati ...

  9. matlab学习笔记10_4MATLAB中的字符串表示

    一起来学matlab-字符串操作 10_4 MATLAB中的字符串表示 觉得有用的话,欢迎一起讨论相互学习~Follow Me 参考书籍 <matlab 程序设计与综合应用>张德丰等著 感 ...

  10. django项目模型字段

    一个模型(model)就是一个单独的.确定的数据的信息源,包含了数据的字段和操作方法.通常,每个模型映射为一张数据库中的表. 基本的原则如下: 每个模型在Django中的存在形式为一个Python类 ...