ADO.NET 七(一个例子)
通过一个完整的实例实现课程信息管理功能的操作,包括查询、修改、删除课程信息等操作。
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 七(一个例子)的更多相关文章
- 用thinkphp写的一个例子:抓取网站的内容并且保存到本地
我需要写这么一个例子,到电子课本网下载一本电子书. 电子课本网的电子书,是把书的每一页当成一个图片,然后一本书就是有很多张图片,我需要批量的进行下载图片操作. 下面是代码部分: public func ...
- 《The art of software testing》的一个例子
这几天一直在看一本书,<The art of software testing>,里面有一个例子挺有感触地,写出来和大家分享一下: [问题] 从输入对话框中读取三个整数值,这三个整数值代表 ...
- spring笔记--使用springAPI以及自定义类 实现AOP的一个例子
Spring的另一个重要思想是AOP,面向切面的编程,它提供了一种机制,可以在执行业务前后执行另外的代码,Servlet中的Filter就是一种AOP思想的体现,下面通过一个例子来感受一下. 假设我们 ...
- ReCap 360 photo照片建模技术的又一个例子
这是我做的又一个利用Autodesk ReCap 360 照片建模技术做的一个例子.你可以下载模型自己把玩,或者下载原始照片自己试一试. 拍摄工具: 小米手机 照片数量:约120张 后期处理工具: p ...
- 从一个例子中体会React的基本面
[起初的准备工作] npm init npm install --save react react-dom npm install --save-dev html-webpack-plugin web ...
- Erlang 程序引发共享内存 bug 的一个例子
虽然 Erlang 的广告说得非常好,functional.share-nothing.消息传递,blah blah 的,好像用 Erlang 写并发程序就高枕无忧了,但是由于 Erlang 信奉高度 ...
- 对Jena的简单理解和一个例子
本文简单介绍Jena(Jena 2.4),使用Protégé 3.1(不是最新版本)创建一个简单的生物(Creature)本体,然后参照Jena文档中的一个例子对本体进行简单的处理,输出本体中的Cla ...
- 使用flume的一个例子
新项目中需要使用到hadoop和vertica,使用flume把数据加载到hadoop中,我做了一个例子, 即监控一个sharefolder,如果里面有文件,则会文件load到hadoop. 开启Fl ...
- php部分--面向对象三大特性-封装(另加连续调用的一个例子)、继承(重写、重载的例子)、多态;
一.封装性: 目的:为了使类更加安全. 做法:1设置私有成员 2在类中建方法,访问私有成员 3在方法里边加控制(if) 私有成员访问的两种方法: 方法一:set(可写) get(可读)做方法(可读可写 ...
- Spark小课堂Week7 从Spark中一个例子看面向对象设计
Spark小课堂Week7 从Spark中一个例子看面向对象设计 今天我们讨论了个问题,来设计一个Spark中的常用功能. 功能描述:数据源是一切处理的源头,这次要实现下加载数据源的方法load() ...
随机推荐
- Linux系统学习(一)一Linux介绍
一.Linux初识 1.1 Linux是什么 Linux是一种自由和开放源码的类UNIX操作系统,使用Linux内核.目前存在着许多不同的Linux发行版,可安装在各种各样的电脑硬件设备,从手机.平板 ...
- NCCloud
NC后台核心服务开发模式不变 NC原Client代码废弃 增加NC Web端Java代码 增加前端JS代码 原有的NC公共能力基本保留:模板.精度.自定义项等
- 去掉 vue 的 "You are running Vue in development mode" 提示
去掉 vue 的 "You are running Vue in development mode" 提示 在项目的 main.js 中已经配置了 Vue.config.produ ...
- SQLSERVER根据提成比率区间计算业绩提成
USE [Employee] GO /****** Object: Table [dbo].[Commission] Script Date: 2019/11/17 14:10:21 ******/ ...
- clion 查看代码 多次查看后如何一步一步回退到最初查看的代码位置
在settings->keymap里面搜索navigate,然后就有蓝色字体的Back.Forward,这个两个有自己对应的快捷键,但是你有可能不能使用这个功能,因为在不同的操作系统里面,有可能 ...
- 关于Django中的数据库操作API之distinct去重的一个误传
转载自http://www.360doc.com/content/18/0731/18/58287567_774731201.shtml django提供的数据库操作API中的distinct()函数 ...
- docker 安装redis cluster集群
安装Redis镜像 docker pull yyyyttttwwww/redis 创建redis容器 docker run -it -d --name r1 -p 5001:6379 --net=ne ...
- odoo开发笔记--日期or时间字段给定默认值
开发中经常有这样的场景,需要给某个日期或者时间的字段默认值: 例如: 日期,默认今天 时间,默认当前时间 可以在odoo模型定义中进行设置, 如下样例提供参考: test_data = fields. ...
- notepadd++中,如何根据某个字符将一行内容切割成多行?
背景描述: 今天在做个事情,遇到下面字符,就想将每个词,如cluster,zookeeper都单独的一行 [cluster, activemq, controller, brokers, zookee ...
- django 表操作
添加表纪录 # Create your models here. class Book(models.Model): id = models.AutoField(primary_key=True) t ...