在控制台程序中实现以下功能:

1. 构建3个表(程序启动时自动建立)  (20分):

1) Employee 职工表 (工号、姓名、性别、年龄、部门)  (Num、Name、Sex、Age、Department)

2) Wage工资表 (编号、工资金额)  (No、Amount)

3) Attend出勤表 (工号、工资表编号、出勤数)  (Num、No、Attendance)

2. 在程序初始化完成后,要求有以下四个选项和功能:

1) 插入相关记录(通过指定文件内容批量导入数据、工号不能有重复)。 (20分)

2) 查询工资为指定金额的职工工号和姓名。(10分)

3) 查询出勤数为0的职工姓名和工号。(10分)

4) 查询出勤数为10并且工资金额小于2500的职工信息。(10分)

注意:

a) 主键、外键关系通过代码建立、适当地考虑效率问题。(10分)

b) 有相应的异常处理(最好有相应的Log输出)。(10分)

c) 提示语合理、程序运行稳定。(10分)

代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data; // State variables
using System.Globalization;
using System.Data.SqlClient; // Date
using System.IO;
using System.Text.RegularExpressions;
using System.Linq.Expressions; namespace ADO.NETCheck
{
class Program
{
//用户输入值
string userInput;
//入口
static void Main(string[] args)
{
Program p = new Program();
p.InitDB();
bool flag = true;
while (flag)
{ if (p.MenuReturn() == true)
{
p.Action();
}
else
{
flag = false;
}
}
}
//返回菜单的选择结果
private bool MenuReturn()
{
//输入1添加员工信息——a
Console.WriteLine("Enter a to add employee info——a");
//输入2查询工资金额为指定金额的职工工号和姓名——b
Console.WriteLine("Enter b to check the employee with the specific wage——b");
//输入3查询出勤率为0的职工姓名和工号——c
Console.WriteLine("Enter c to check the employee whose attendance=0——c");
//输入4查询出勤率为10并且工资金额小于2500的职工信息——d
Console.WriteLine("Enter d to check the employee whose attendance=10 and wage<=2500——d");
//请输入(输入‘a’、‘b’、‘c’、‘d’以外的字符将退出程序)
Console.Write("Please enter (words other than 'a','b','c','d' means quit):");
string reg = "^[a,b,c,d]$";
//ReadLine会自动从输入中刨除回车
userInput = Console.ReadLine();
if (Regex.IsMatch(userInput.ToString(), @reg))
{
return true;
}
else
{
return false;
}
}
//判断用户选择的操作
private void Action()
{
if (userInput == "a")
{
AddEmployeeInfo();
}
if (userInput == "b")
{
Console.Write("Please enter the wage you want to check:");
string wageLimit = Console.ReadLine();
checkWage(wageLimit);
}
if (userInput == "c")
{
Console.Write("Please enter the attendance number you want to check:");
string attNumString = Console.ReadLine();
int attNum = int.Parse(attNumString);
checkAttend(attNum);
}
if (userInput == "d")
{
checkAttendAndWage();
} Console.ReadKey();
}
//插入相关记录——a
private void AddEmployeeInfo()
{
string connectionString = @"server=TYLAN_AIO;database=tylanDB;Trusted_Connection=True;";
//生命周期开始自动回收
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
//读取文件中的employee信息
string employeeReadPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\employees.txt";
var lines = File.ReadLines(@employeeReadPath);
List<string> txt = new List<string>();
foreach (var line in lines)
{
txt.Add(line);
}
txt.ForEach(t =>
{
string[] keyValues = t.Split(',');
//一定要注意严格遵守VALUES('','','')的格式不要忘记加单引号''
command.CommandText += "INSERT INTO Employee VALUES ('" + keyValues[] + "','" + keyValues[] + "','" + keyValues[] + "','" + keyValues[] + "','" + keyValues[] + "') ";
try
{
command.ExecuteNonQuery();
}
catch (Exception ex)
{
WriteLog(ex);
}
});
//读取文件中的wages信息
command.CommandText = null;
string wagesReadPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\wages.txt";
lines = File.ReadLines(@wagesReadPath);
List<string> txt1 = new List<string>();
foreach (var line in lines)
{
txt1.Add(line);
}
txt1.ForEach(t =>
{
string[] keyValues = t.Split(',');
//一定要注意严格遵守VALUES('','','')的格式不要忘记加单引号''
command.CommandText += "INSERT INTO Wage VALUES ('" + keyValues[] + "','" + keyValues[] + "') ";
try
{
command.ExecuteNonQuery();
}
catch (Exception ex)
{
WriteLog(ex);
}
});
//读取文件中的attendances信息
command.CommandText = null;
string attendReadPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\attendances.txt";
lines = File.ReadLines(@attendReadPath);
List<string> txt2 = new List<string>();
foreach (var line in lines)
{
txt2.Add(line);
}
txt2.ForEach(t =>
{
string[] keyValues = t.Split(',');
//一定要注意严格遵守VALUES('','','')的格式不要忘记加单引号''
command.CommandText += "INSERT INTO Attend VALUES ('" + keyValues[] + "','" + keyValues[] + "','" + keyValues[] + "') ";
try
{
command.ExecuteNonQuery();
}
catch (Exception ex)
{
WriteLog(ex);
}
});
connection.Close();
}
}
//查询工资金额为指定金额的职工工号和姓名——b
private void checkWage(string wage)
{
string connectionString = @"server=TYLAN_AIO;database=tylanDB;Trusted_Connection=True;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "select Employee.Num,Employee.Name from Employee left join Attend on(Attend.Num = Employee.Num) left join Wage on(Wage.No = Attend.No) where (Wage.Amount = '" + wage + "')";
try
{
SqlCheck(command);
}
catch (Exception ex)
{
WriteLog(ex);
}
connection.Close();
}
}
//查询出勤率为0的职工姓名和工号——c
private void checkAttend(int att)
{
string connectionString = @"server=TYLAN_AIO;database=tylanDB;Trusted_Connection=True;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "select Employee.Num,Employee.Name from Employee join Attend on(Attend.Num = Employee.Num) where (Attend.Attendance = '" + att + "')";
try
{
SqlCheck(command);
}
catch (Exception ex)
{
WriteLog(ex);
}
connection.Close();
}
}
//查询出勤率为10并且工资金额小于2500的职工信息——d
private void checkAttendAndWage()
{
string connectionString = @"server=TYLAN_AIO;database=tylanDB;Trusted_Connection=True;";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "select * from Employee left join Attend on(Attend.Num = Employee.Num) left join Wage on(Wage.No = Attend.No) where (Wage.Amount < 2500 AND Attend.Attendance = 10)";
try
{
SqlCheck(command);
}
catch (Exception ex)
{
WriteLog(ex);
}
connection.Close();
}
}
//数据库查询并返回结果的方法
private void SqlCheck(SqlCommand command)
{
//执行查询并将查询结果填充到数据集
SqlDataAdapter sqlDA = new SqlDataAdapter();
sqlDA.SelectCommand = command;
DataSet ds = new DataSet();
sqlDA.Fill(ds);
if (ds.Tables[].Rows.Count != )
{
//遍历并打印数据集
foreach (DataRow dr in ds.Tables[].Rows)
{
foreach (DataColumn dc in ds.Tables[].Columns)
{
Console.Write(dc + ":");
Console.WriteLine(dr[dc].ToString());
}
}
}
else
{
Console.WriteLine("No suitable result.");
}
}
//初始化数据库方法
public void InitDB()
{
try
{
string connectionString = @"server=TYLAN_AIO;database=tylanDB;Trusted_Connection=True;";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "create table Employee(Num int NOT NULL,Name varchar(50),Sex varchar(50),Age int,Department varchar(50)) ";
command.CommandText += "create table Wage(No int NOT NULL,Amount money) ";
command.CommandText += "create table Attend(Num int NOT NULL,No int,Attendance int) ";
//Add primary key.
command.CommandText += "alter table Employee add constraint PK_Num primary key(Num) ";
command.CommandText += "alter table Wage add constraint PK_No primary key(No) ";
command.CommandText += "alter table Attend add constraint PK_NumAttend primary key(Num) ";
//Add foreign key.
command.CommandText += "alter table Attend add constraint FK_Num foreign key(Num) references Employee(Num) ";
command.CommandText += "alter table Attend add constraint FK_No foreign key(No) references Wage(No) ";
command.ExecuteNonQuery();
connection.Close();
}
catch (Exception ex)
{
WriteLog(ex);
}
}
//异常log打印方法
public void WriteLog(Exception ex)
{
string logUrl = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\ADOlog.txt";
if (File.Exists(@logUrl))
{
FileStream fs = new FileStream(logUrl, FileMode.Append);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
try
{
sw.Write(ex);
}
catch (Exception ex1)
{
WriteLog(ex1);
}
finally
{
sw.Close();
fs.Close();
}
}
else
{
FileStream fs = new FileStream(logUrl, FileMode.CreateNew);
StreamWriter sw = new StreamWriter(fs, Encoding.Default);
try
{
sw.Write(ex);
}
catch (Exception ex1)
{
WriteLog(ex1);
}
finally
{
sw.Close();
fs.Close();
}
}
}
}
}

运行如下:

输入a会将桌面上三个文件employees.txt,attendances.txt和wages.txt中的数据添加到相应的数据库表中。

文件格式如下:

初始化以及插入数据后的数据库表像下面这样:

本次主要练习了ADO.NET关于在数据库SQL Server中进行增删改查的一些操作,也用到了文件流,泛型和lambda,异常处理以及生命周期的一些简单应用。

希望大家能多提改进方面的意见并给出相应代码:)

C#中一道关于ADO.NET的基础练习题的更多相关文章

  1. 在Visual C++中的用ADO进行数据库编程

    1. 生成应用程序框架并初始化OLE/COM库环境 创建一个标准的MFC AppWizard(exe)应用程序,然后在使用ADO数据库的InitInstance函数中初始化OLE/COM库(因为ADO ...

  2. (原创)超详细一步一步在eclipse中配置Struts2环境,无基础也能看懂

    (原创)超详细一步一步在eclipse中配置Struts2环境,无基础也能看懂 1. 在官网https://struts.apache.org下载Struts2,建议下载2.3系列版本.从图中可以看出 ...

  3. 转:机器学习中的算法(2)-支持向量机(SVM)基础

    机器学习中的算法(2)-支持向量机(SVM)基础 转:http://www.cnblogs.com/LeftNotEasy/archive/2011/05/02/basic-of-svm.html 版 ...

  4. C#中使用泛型对照使用通用基础类型效率减少近一倍

     C#中使用泛型对照使用通用基础类型效率减少近一倍 以下是測试结果: CSharp class and generic TotalMilliseconds: 270772.9229CSharp g ...

  5. php二维数组中的查找(善于利用基础函数)

    php二维数组中的查找(善于利用基础函数) 一.总结 真没必要完整的写函数,善于借用 1.array_search()是在以为数组中来找,现在我们要在二维数组数组中来,肯定要借用这个 2.!==fal ...

  6. Linux基础练习题(二)

    Linux基础练习题(二) 1.复制/etc/skel目录为/home/tuer1,要求/home/tuser1及其内部文件的属组和其它用户均没有任何访问权限. [root@www ~]# cp -r ...

  7. 珍藏的数据库SQL基础练习题答案

    自己珍藏的数据库SQL基础练习题答案 一,基本表的定义与删除. 题1: 用SQL语句创建如下三张表:学生(Student),课程表(Course),和学生选课表(SC),这三张表的结构如表1-1到表1 ...

  8. Linux基础练习题之(四)

    Linux基础练习题 请详细总结vim编辑器的使用并完成以下练习题 1.复制/etc/rc.d/rc.sysinit文件至/tmp目录,将/tmp/rc.sysinit文件中的以至少一个空白字符开头的 ...

  9. Python之基础练习题

    Python之基础练习题 1.执行 Python 脚本的两种方式 2.简述位.字节的关系 解:8位是一个字节 3.简述 ascii.unicode.utf-8.gbk 的关系 4.请写出 “李杰” 分 ...

随机推荐

  1. gdb 读取elf

    在make file中找到ld,然后将其换成 gdb, 如本例中LINKER = /usr/cygnus/xscale-020523/H-sparc-sun-solaris2.5/bin/xscale ...

  2. .NET 垃圾回收机制要点整理

    1. .NET资源分托管资源和非托管资源,对于托管资源,.NET GC可以很好的回收无用的垃圾,而对于非托管(例如文件访问,网络访问等)需要手动清理垃圾(显式释放). 2. 非托管资源的释放,.NET ...

  3. Spring框架文档与API(4.3.6版本)

    http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/ Table of Contents I ...

  4. StringBuilder.AppendFormat(String, Object, Object) 方法

    将通过处理复合格式字符串(包含零个或零个以上格式项)返回的字符串追加到此实例. 每个格式项都替换为这两个参数中任意一个参数的字符串表示形式. 说明: public StringBuilder Appe ...

  5. iOS10 完美降级 iOS9.3.2,保留全部数据

    本篇文章由:http://xinpure.com/downgrade-ios10-perfect-ios9-3-2-retention-of-all-data/ iOS 10 Beta版尝鲜 前段时间 ...

  6. 锋利的jQuery(第二版)源码下载地址

    书上给的http://cssrain.sinaapp.com无法访问 问作者邮箱要的: 第1版源码:百度云盘下载:http://pan.baidu.com/share/link?shareid=104 ...

  7. WordPress 博客文章中google adsense广告展示方法之一

    http://log.medcl.net/item/2011/08/diving-into-elasticsearch-4-installation-and-configuration/ 看到这个网站 ...

  8. 【js】正则表达式(I)

    正则表达式是由英文词语regular expression翻译过来的,就是符合某种规则的表达式.正则表达式在软件开发中应用非常广泛,例如,找出网页中的超链接,找出网页中的email地址,找出网页中的手 ...

  9. selenium2.0关于python的常用函数

    转: 新建实例driver = webdriver.Chrome() 1.获取当前页面的Url函数 方法:current_url 实例: driver.current_url 2.获取元素坐标 方法: ...

  10. jmeter 非GUI执行测试,导入jtl文件没有响应数据出来办法

    jemter 官方也一直强调要在非GUI下执行 Run your JMeter test in command-line non-GUI mode as 在linux下执行jmeter压力测试,生成j ...