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() ...
随机推荐
- Java串口通信--------基于RXTX (附带资源地址)
最近帮老师做了一个小项目,一个牧场公司想用传感器收集一些环境信息,记录到数据库里去,然后加以分析查看.这里面和传感器通信用到了串口通信,我也是接触了一下,把用到的东西分享出来. 准备工作: RXTX: ...
- D3.js的v5版本入门教程(第十章)
在这一章我们干点有趣的事——让我们上一章绘制的图表动起来,这样岂不是很有意思 为了让图表动起来,我们还是需要以下新的知识点 .attr(xxx) .transition() .attr(xxx),tr ...
- 【pytorch 代码】pytorch 网络结构可视化
部分内容转载自 http://blog.csdn.net/GYGuo95/article/details/78821617,在此表示由衷感谢. 此方法需要安装python-graphviz: con ...
- NIO 选择器 Selector
选择器提供选择执行已经就绪的任务的能力,这使得多元 I/O 成为可能.就像在第一章中描述的那样,就绪选择和多元执行使得单线程能够有效率地同时管理多个 I/O 通道(Channels).C/C++代码的 ...
- Unity内存优化之视频讲解
视频为中文讲解,mp4格式,大小3.05GB 目录 扫码时备注或说明中留下邮箱 付款后如未回复请至https://shop135452397.taobao.com/ 联系店主
- PHP正则匹配中文汉字会得到�
preg_match('/^[a-zA-Z\x{4e00}-\x{9fa5}]+$/u', $str)
- MySQL8新特性(2)--mysql的升级过程
在之前的版本中,安装新的版本mysql之后,mysql server在下一次启动时,会自动升级数据字典表,然后dba需要执行mysql_upgrade手动升级mysql schema中的系统表,以及其 ...
- 【转载】 《Human-level concept learning through probabilistic program induction》阅读笔记
原文地址: https://blog.csdn.net/ln1996/article/details/78459060 --------------------- 作者:lnn_csdn 来源:CSD ...
- MD5(3)
import java.io.UnsupportedEncodingException; import java.security.PrivateKey; import java.security.S ...
- k8s记录-kubectl常用
kubectl create/delete -f xxx.yml kubectl get all -A kubectl get pods -o wide kubectl describe pods p ...