基于OOP实现对象添加到数据库
//初始化内容应该写在构造方法里面
//定义一个数据层访问对象
private StudentService objStudentService = new StudentService();
//封装学员对象
Student objStudent = new Student()
{
StudentName = this.txtStudentName.Text.Trim(),
Gender =this.rdoFemale.Checked?"男":"女",
Birthday = Convert.ToDateTime(this.dtpBirthday.Text),
Age = DateTime.Now.Year - Convert.ToDateTime(this.dtpBirthday.Text).Year,
ClassId = Convert.ToInt32(this.cboClassName.SelectedValue),
StudentIdNo = this.txtStudentIdNo.Text.Trim(),
CardNo = this.txtCardNo.Text.Trim(),
PhoneNumber = this.txtPhoneNumber.Text.Trim(),
StudentAddress = this.txtPhoneNumber.Text.Trim(),
StuImage = this.pbStu.Image ==null?"":new SerializeObjectToString().SerializeObject(this.pbStu.Image),
};
//提交对象
try
{
int result = objStudentService.AddStudent(objStudent);
if (result == 1)
{
DialogResult dresult = MessageBox.Show("添加成功,继续添加么", "添加询问", MessageBoxButtons.OKCancel,MessageBoxIcon.Question);
if (dresult == DialogResult.OK)
{
//清空当前文本框
foreach (Control item in this.groupBox1.Controls)
{
if (item is TextBox)
item.Text = "";
else if (item is RadioButton)
((RadioButton)item).Checked = false;
else if (item is ComboBox)
((ComboBox)item).SelectedIndex = -1;
}
this.pbStu.Image = null;
this.txtStudentName.Focus();
}
}
else MessageBox.Show("添加失败", "添加提示");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "信息提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
//判断是否保存成功
}
/// <summary>
/// 添加学员对象
/// </summary>
/// <param name="objStudent"></param>
/// <returns></returns>
public int AddStudent(Student objStudent)
{
string sql = "insert into Students (StudentName,Gender,Birthday,Age,ClassId,StudentIdNo,CardNo,PhoneNumber,StudentAddress,StuImage) ";
sql += "values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}')";
sql = string.Format(sql, objStudent.StudentName,objStudent.Gender,objStudent.Birthday, objStudent.Age,
objStudent.ClassId, objStudent.StudentIdNo,objStudent.CardNo, objStudent.PhoneNumber,
objStudent.StudentAddress, objStudent.StuImage);
try
{
return SQLHelper.Update(sql);
}
catch (Exception ex)
{
throw new Exception("保存数据出现问题!"+ex.Message);
}
}