XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="程序集" value="StudentManager"/>
<add key="命名空间" value="StudentManager"/>
<add key="类" value="SqlStudentDAL"/>
</appSettings>
</configuration>
DBHelper
namespace StudentManager
{
public class DBHelper
{
/// <summary>
/// 获得连接字符串,使用sql数据库
/// </summary>
private static string constring ="server=.;uid=sa;database=StudentManager;pwd=";
/// <summary>
/// 执行增删改操作
/// </summary>
/// <param name="sql">传入增删改的sql语句</param>
/// <returns>返回受影响的行数</returns>
public static int ExecuteNonQuery(string sql)
{
int i=0;
using(SqlConnection con = new SqlConnection(constring))
{
using (SqlCommand cmd = new SqlCommand(sql,con))
{
con.Open();
i= cmd.ExecuteNonQuery();
con.Close();
}
}
return i;
}
/// <summary>
/// 执行查询操作
/// </summary>
/// <param name="sql">查询语句</param>
/// <returns>返回查询结果</returns>
public static SqlDataReader ExecuteReader(string sql)
{
SqlConnection con = new SqlConnection(constring);
SqlCommand cmd = new SqlCommand(sql, con);
cmd.Connection.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
}
工厂类
public class Factory
{
public static IStudent CreateStudentDAL()
{
IStudent idal = null;
//从配置文件中加载程序集的名称
string 程序集 = System.Configuration.ConfigurationManager.AppSettings["程序集"];
string 命名空间 = System.Configuration.ConfigurationManager.AppSettings["命名空间"];
//从配置文件中加载数据访问层的名称
string 类 = System.Configuration.ConfigurationManager.AppSettings["类"];
//通过反射创建数据访问对象
idal = (IStudent)Assembly.Load(程序集).CreateInstance(命名空间+"."+类);
return idal;
}
}
form1
namespace StudentManager
{
public partial class Form1 : Form
{
// bool Flag = false;//标志位,表示用户是否选择过要修改或删除的数据行。
int id;
//通过工厂创建对象
IStudent studal = Factory.CreateStudentDAL();
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 窗体加载时,显示所有信息
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ReadOnly = true;//不允许用户修改行
SE.SkinFile = Application.StartupPath + "\\skin\\OneGreen.ssk";
StudentView();
}
private void StudentView()
{
dataGridView1.DataSource = studal.GetAll();
}
//查看学生信息
private void btnView_Click(object sender, EventArgs e)
{
StudentView();
}
//添加学生信息
private void btnAdd_Click(object sender, EventArgs e)
{
if (txtName.Text == "" || txtAge.Text == "")
{
MessageBox.Show("请将信息填写完整", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Stop);
return;
}
try
{
int.Parse(txtAge.Text);
}
catch
{
MessageBox.Show("年龄必须为整数","输入错误",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
}
string name = txtName.Text;
if (studal.SelectByUserName(name))
{
MessageBox.Show("该学生已存在,请与管理员联系","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information );
return;
}
//添加学生方法1
string gender = radMale.Checked ? radMale.Text : radFemale.Text;
//父类引用指向子类,调用子类的方法
int i = studal.AddStudent(txtName.Text, txtAge.Text, gender, dtpCreateDate.Value);
//添加学生方法2
//StudentModel studentModel = new StudentModel();
//studentModel.Stuname = txtName.Text;
//studentModel.Gender = radMale.Checked ? radMale.Text : radFemale.Text;
//studentModel.CreateDate = dtpCreateDate.Value;
//int i = studal.AddStudent(studentModel);
if (i > 0)
{
MessageBox.Show("添加成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
// btnView.PerformClick();
StudentView();
}
else
{
MessageBox.Show("添加学生时产生了系统错误,请与管理员联系。", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
}
//判断是否选中某行
private void dataGridView1_Click(object sender, EventArgs e)
{
//整行选中
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//判断是否选中某行
if (dataGridView1.SelectedRows.Count > 0)
{
int id = dataGridView1.CurrentRow.Index;
// int id = int.Parse(dataGridView1.SelectedRows[0].Cells[0].Value.ToString());
txtName.Text = dataGridView1.SelectedRows[0].Cells["Column2"].Value.ToString();
radMale.Checked = true;
if (dataGridView1.SelectedRows[0].Cells["Column3"].Value.ToString() == "女")
{
radFemale.Checked = true;
}
txtAge.Text = dataGridView1.SelectedRows[0].Cells["Column4"].Value.ToString();
dtpCreateDate.Text = dataGridView1.SelectedRows[0].Cells["Column5"].Value.ToString();
}
else {
MessageBox.Show("请先选中要更新的行","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information );
}
}
//更新学生信息
private void btnUpdate_Click(object sender, EventArgs e)
{
//获取当前选中的索引
id = int.Parse( dataGridView1.SelectedRows[0].Cells["Column1"].Value.ToString());
string sex = radMale.Checked ? radMale.Text : radFemale.Text;
try
{
int.Parse(txtAge.Text);
}
catch
{
MessageBox.Show("年龄必须为整数", "输入错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
if (txtName.Text == "" || txtAge.Text == "" || dtpCreateDate.Text == "")
{
MessageBox.Show("请输入详细的学生信息","提示",MessageBoxButtons .OK ,MessageBoxIcon.Information );
return;
}
int i = studal.updateStudent(txtName.Text, txtAge.Text, sex, dtpCreateDate.Value, id);
if (i > 0)
{
MessageBox.Show("更新成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
StudentView();
}
else
{
MessageBox.Show("更新失败", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//删除学生信息
private void btnDelete_Click(object sender, EventArgs e)
{
//dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
//if(Flag ==false)
//{
// MessageBox.Show("请选择要删除的行","提示",MessageBoxButtons .OK ,MessageBoxIcon.Warning );
// return;
//}
if (MessageBox.Show("确实要删除吗?", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.No)
{
return;
}
id = int.Parse(dataGridView1.SelectedRows[0].Cells["Column1"].Value.ToString());
int i = studal.deleteStudent(id);
if (i > 0)
{
MessageBox.Show("删除成功", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
StudentView();
}
else
{
MessageBox.Show("删除失败", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
//序列化查看
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = userable.getUser();
}
//序列化
private void button1_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("e:\\student.bat",FileMode .Create );
BinaryFormatter bf = new BinaryFormatter();
DataTable dt = (DataTable)dataGridView1.DataSource;
bf.Serialize(fs,dt);
dataGridView1.DataSource = null;
fs.Close();
fs.Dispose();
MessageBox.Show("已将数据序列化");
}
//反序列化
private void button2_Click(object sender, EventArgs e)
{
FileStream fs = new FileStream("e:\\student.bat",FileMode .Open );
BinaryFormatter bf = new BinaryFormatter();
DataTable dt = bf.Deserialize(fs) as DataTable;
fs.Close();
fs.Close();
MessageBox.Show("反序列化成功");
}
}
DAL
namespace StudentManager
{
/// <summary>
/// 具体产品,连接到sql数据库
/// </summary>
public class SqlStudentDAL :IStudent
{
/// <summary>
/// 查询所有信息
/// </summary>
/// <returns>泛型集合</returns>
public List<StudentModel> GetAll()
{
string sql = "select * from Student";
List<StudentModel> list = new List<StudentModel>();
SqlDataReader reader = DBHelper.ExecuteReader(sql);
while(reader.Read())
{
StudentModel stuModel = new StudentModel();
stuModel.Id = reader["id"].ToString();
stuModel.Stuname = reader["stuname"].ToString();
stuModel.Gender = reader["Gender"].ToString();
stuModel.Age = reader["Age"].ToString();
stuModel.CreateDate = DateTime.Parse(reader["CreateDate"].ToString());
list.Add(stuModel);
}
reader.Close();
return list;
}
/// <summary>
/// 添加学生
/// </summary>
/// <param name="studentModel">传入学生类</param>
/// <returns>返回影响的行数</returns>
public int AddStudent(StudentModel studentModel)
{
string sql =string.Format( "insert into Student values('{0}','{1}',{2},'{3}')",studentModel.Stuname,studentModel.Gender,studentModel.Age,studentModel.CreateDate);
return DBHelper.ExecuteNonQuery(sql);
}
/// <summary>
/// 添加学生---------方法重载
/// </summary>
/// <param name="name">姓名</param>
/// <param name="age">年龄</param>
/// <param name="gender">性别</param>
/// <param name="crreateDate">日前</param>
/// <returns>返回影响的行数</returns>
public int AddStudent(string name, string age, string gender, DateTime crreateDate)
{
string sql = string.Format("insert into Student values('{0}','{1}',{2},'{3}')", name, gender, age, crreateDate);
return DBHelper.ExecuteNonQuery(sql);
}
/// <summary>
/// 根据用户名查找用户
/// </summary>
/// <param name="UserName">用户名</param>
/// <returns></returns>
public bool SelectByUserName(string name)
{
string sql = string .Format ("select * from Student where stuname='{0}'",name);
SqlDataReader reader = DBHelper .ExecuteReader (sql);
return reader.HasRows;
}
/// <summary>
/// 更新学生---------方法重载S
/// </summary>
/// <param name="studentModel">学生对象</param>
/// <returns>返回受影响的行数</returns>
public int updateStudent(StudentModel studentModel)
{
string sql = string.Format("update Student set stuname='{0}',Gender='{1}',Age='{2}',CreateDate='{3}' where id='{4}'", studentModel.Stuname, studentModel.Gender, studentModel.Age, studentModel.CreateDate, studentModel.Id);
return DBHelper.ExecuteNonQuery(sql);
}
public int updateStudent(string name, string age, string gender, DateTime crreateDate, int id)
{
string sql = string.Format("update Student set stuname='{0}',Age='{1}',Gender='{2}',CreateDate='{3}' where id='{4}'", name, age, gender, crreateDate, id);
return DBHelper.ExecuteNonQuery(sql);
}
/// <summary>
/// 执行删除操作
/// </summary>
/// <param name="id">要删除的行号</param>
/// <returns></returns>
public int deleteStudent(int id)
{
string sql = string.Format("delete from Student where id='{0}'",id );
return DBHelper.ExecuteNonQuery(sql);
}
}
}
namespace StudentManager
{
/// <summary>
/// 抽象产品
/// </summary>
public interface IStudent
{
List<StudentModel> GetAll();
//增加学生
int AddStudent(StudentModel studentModel);
int AddStudent( string name, string age, string gender, DateTime crreateDate);
//根据学生姓名查找用户信息
bool SelectByUserName(string name);
//更新学生信息
int updateStudent(StudentModel studentModel);
int updateStudent(string name, string age, string sex, DateTime crreateDate, int id);
//删除学生
int deleteStudent(int id);
}
}
创建序列化
namespace StudentManager
{
[Serializable]
public class userable
{
public static DataTable getUser()
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("stuname");
dt.Columns.Add("Gender");
dt.Columns.Add("Age");
dt.Columns.Add("CreateDate");
DataRow row = dt.NewRow ();
row[0]=1;
row[1]="cn129";
row[2]="男";
row[3]=20;
row[4] = "2009-6-8";
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 2;
row[1] = "cn123";
row[2] = "男";
row[3] = 23;
row[4] = "2009-6-8";
dt.Rows.Add(row);
return dt;
}
}
}
![]()
namespace StudentManager
{
//实体类,这个类的每一个对象,表示数据库中的一条记录,即一个学生
public class StudentModel
{
//封装字段
//学号
private string _id;
public string Id
{
get { return _id; }
set { _id = value; }
}
//姓名
private string _stuname;
public string Stuname
{
get { return _stuname; }
set { _stuname = value; }
}
//性别
private string _Gender;
public string Gender
{
get { return _Gender; }
set { _Gender = value; }
}
//年龄
private string _Age;
public string Age
{
get { return _Age; }
set
{
_Age = value;
}
}
//入学时间
private DateTime _CreateDate;
public DateTime CreateDate
{
get { return _CreateDate; }
set { _CreateDate = value; }
}
/// <summary>
/// 构造函数
/// </summary>
public StudentModel() { }
public StudentModel(string id,string stuname,string gender,string age,DateTime createDate)
{
this._id = id;
this._stuname = stuname;
this._Gender = gender;
this._Age = age;
this._CreateDate = createDate;
}
}
}
浙公网安备 33010602011771号