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

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. 自己写的一个读取execl的帮助类

    目标:读取execl的第一个sheet,并传入不需要读取的表头的行数,返回该execl里所有数据的list 解析共有2种:1.DOM      2.SAX import java.io.File; i ...

  2. CentOS 查看系统版本号

    查看centos版本: cat /etc/issuecat /etc/redhat-release 查看系统位数: getconf LONG_BIT 查看内核版本: uname -r cat /pro ...

  3. CentOS关闭休眠和屏保模式

    CentOS关闭休眠和屏保模式   本人因为特殊需求,想让某台Linux主机始终显示某个程序,显示器不能关机或者休眠或进入屏保模式. 环境:Ubuntu 11.10 最小化模式安装并安装有轻量级桌面o ...

  4. 触发器学习笔记(:new,:old用法)

    触发器学习笔记(:new,:old用法) 触发器是数据库发生某个操作时自动运行的一类的程序         用于保持数据的完整性或记录数据库操作信息方面         触发器不能够被直接调用,只能够 ...

  5. coding云进行git push报:permission denied

    1.原因可能是 登录其他的git 项目,本地缓存了其他用户的 用户名和密码 认证信息,导致一直权限不通过 解决: git remote add origin http://yourname:passw ...

  6. Python 的 Matplotlib 画图库

    Matplotlib安装 NumPy库方便数值运算,但枯燥的数据并不利于人们的直观理解. 数据需要可视化. Matplotlib:一个数据可视化函数库 使用前需要安装  利用Python自带 ...

  7. python练习笔记——用函数对列表奇偶分类,且过程不增加新列表

    编写一个函数:函数接收一个列表,将列表中所有的奇数,放到偶数之前,要求过程中不增加新的列表 def fun(*args): # 因为奇数放在偶数之前,标记出奇数中的偶数 # 并将该偶数取出放在数列的最 ...

  8. (一)RocketMq入门之安装运行

    一.几个重要的地址 Git地址:https://github.com/apache/incubator-rocketmq 编译好的文件:https://rocketmq.incubator.apach ...

  9. Cocos2d-x游戏移植到WP8之路 -- c++和c#交互

    Cocos2d-x是眼下最流行的手机游戏引擎之中的一个,开源.轻量.多平台等的诸多特性使得它被非常多国内外手游开发人员所喜爱. 利用Cocos2d-x来开发Windows Phone 8的游戏相同也是 ...

  10. POJ 1789:Truck History(prim&amp;&amp;最小生成树)

    id=1789">Truck History Time Limit: 2000MS   Memory Limit: 65536K Total Submissions: 17610   ...