藉助DBHelper實現學生管理案例分析
一、案例功能的實現
數據:
--專業
create table ProfessionInfo
(
ProfessionID int primary key identity(1,1), --專業編號
professionName varchar(50) not null unique --專業名稱
)
--學生
create table StudentInfo
(
StuID varchar(20) primary key, --學生學號
StuName varchar(50) not null, --學生姓名
StuAge int not null check(StuAge > 0 and StuAge < 130), --學生年齡
StuSex char(2) not null check(StuSex in('男','女')), --學生性別
StuHobby nvarchar(100), --愛好
ProfessionID int not null references ProfessionInfo(ProfessionID), --所屬專業編號
)
--添加專業信息
insert into ProfessionInfo(professionName) values('電子競技')
insert into ProfessionInfo(professionName) values('軟件開發')
insert into ProfessionInfo(professionName) values('醫療護理')
--插入學生信息
insert into StudentInfo(StuID,StuName,StuAge,StuSex,StuHobby,ProfessionID)
values('001','劉備',18,'男','',1)
insert into StudentInfo(StuID,StuName,StuAge,StuSex,StuHobby,ProfessionID)
values('002','關羽',20,'男','',2)
insert into StudentInfo(StuID,StuName,StuAge,StuSex,StuHobby,ProfessionID)
values('003','張飛',19,'男','',2)
insert into StudentInfo(StuID,StuName,StuAge,StuSex,StuHobby,ProfessionID)
values('004','孫尚香',17,'女','',3)
業務需求:
(1)專業下拉框綁定專業表數據,網格控件綁定學生數據,並且點擊”搜索”按鈕可以多條件組合查詢。
(2)選中某一行,右鍵可以彈出”刪除”菜單,點擊”刪除”菜單可以刪除學生數據。
(3)點擊”新增”按鈕,彈出新增窗體,在此窗體中完成學生的新增操作。
(4)選中某一行,點擊”編輯”按鈕,彈出編輯窗體,在此窗體中完成數據的修改。
備註:其中性別的單選框,以及愛好的多選框分別用兩個Pannel容器包含。
實現代碼:
(1)查詢窗體綁定專業信息、綁定學生信息以及搜索功能代碼:
#region 綁定專業信息到下拉框
private void BindProfession()
{
DataTable dt = new DataTable();
DBHelper.PrepareSql("select * from ProfessionInfo");
dt = DBHelper.ExecQuery();
DataRow dr = dt.NewRow();
dr["ProfessionID"] = 0;
dr["professionName"] = "--請選擇--";
dt.Rows.InsertAt(dr, 0);
this.cmbPro.DataSource = dt;
this.cmbPro.DisplayMember = "professionName";
this.cmbPro.ValueMember = "ProfessionID";
}
#endregion
#region 綁定學生數據
private void BindData()
{
string sql = "select * from StudentInfo inner join ProfessionInfo on StudentInfo.ProfessionID=ProfessionInfo.ProfessionID where 1 = 1 ";
if(!this.cmbPro.SelectedValue.ToString().Equals("0"))
sql += " and StudentInfo.ProfessionID = " + this.cmbPro.SelectedValue.ToString();
if(!this.txtName.Text.Equals(""))
sql += " and StuName like '%" + this.txtName.Text + "%'";
this.dataGridView1.AutoGenerateColumns = false;
DBHelper.PrepareSql(sql);
this.dataGridView1.DataSource = DBHelper.ExecQuery();
}
#endregion
private void Form1_Load(object sender, EventArgs e)
{
BindProfession();
BindData();
}
private void btSearch_Click(object sender, EventArgs e)
{
BindData();
}
(2)刪除菜單代碼:
private void 刪除ToolStripMenuItem_Click(object sender, EventArgs e)
{
//添加是否確定刪除的對話框
DialogResult result = MessageBox.Show("確定要刪除數據嗎,刪除之後無法恢復!", "提示框",
MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
if (result == DialogResult.Cancel)
return;
string stuid = this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
string sql = "delete from StudentInfo where StuID = @StuID";
DBHelper.PrepareSql(sql);
DBHelper.SetParameter("StuID", stuid);
int rowCount = DBHelper.ExecNonQuery();
if (rowCount == 1)
MessageBox.Show("刪除成功!");
else
MessageBox.Show("刪除失敗!");
BindData();
}
(3)添加學生信息窗體代碼:
#region 綁定專業信息到下拉框
private void BindProfession()
{
DataTable dt = new DataTable();
DBHelper.PrepareSql("select * from ProfessionInfo");
dt = DBHelper.ExecQuery();
DataRow dr = dt.NewRow();
dr["ProfessionID"] = 0;
dr["professionName"] = "--請選擇--";
dt.Rows.InsertAt(dr, 0);
this.cmbPro.DataSource = dt;
this.cmbPro.DisplayMember = "professionName";
this.cmbPro.ValueMember = "ProfessionID";
}
#endregion
private void FrmAdd_Load(object sender, EventArgs e)
{
BindProfession();
}
private void btAdd_Click(object sender, EventArgs e)
{
string sql = "insert into StudentInfo(StuID,StuName,StuAge,StuSex,StuHobby,ProfessionID) values(@StuID,@StuName,@StuAge,@StuSex,@StuHobby,@ProfessionID)";
DBHelper.PrepareSql(sql);
DBHelper.SetParameter("StuID", this.txtId.Text);
DBHelper.SetParameter("StuName",this.txtName.Text);
DBHelper.SetParameter("StuAge",this.txtAge.Text);
//性別處理
string sex = "";
if (this.rbBoy.Checked == true) sex = this.rbBoy.Text;
if (this.rbGirl.Checked == true) sex = this.rbGirl.Text;
DBHelper.SetParameter("StuSex", sex);
//愛好處理
string hobby = "";
foreach (CheckBox ck in this.panel2.Controls)
{
if (ck.Checked == true)
{
if (!hobby.Equals(""))
hobby += ",";
hobby += ck.Text;
}
}
DBHelper.SetParameter("StuHobby", hobby);
DBHelper.SetParameter("ProfessionID",this.cmbPro.SelectedValue.ToString());
int rowCount = DBHelper.ExecNonQuery();
if (rowCount == 1)
{
MessageBox.Show("新增成功!");
this.Close();
}
else
{
MessageBox.Show("新增失敗!");
}
}
(4)編輯學生信息窗體代碼:
public string StuID { get; set; } //學生編號
#region 綁定專業信息到下拉框
private void BindProfession()
{
DataTable dt = new DataTable();
DBHelper.PrepareSql("select * from ProfessionInfo");
dt = DBHelper.ExecQuery();
DataRow dr = dt.NewRow();
dr["ProfessionID"] = 0;
dr["professionName"] = "--請選擇--";
dt.Rows.InsertAt(dr, 0);
this.cmbPro.DataSource = dt;
this.cmbPro.DisplayMember = "professionName";
this.cmbPro.ValueMember = "ProfessionID";
}
#endregion
private void BindDetail()
{
string sql = "select * from StudentInfo where StuID = " + this.StuID;
DBHelper.PrepareSql(sql);
DataTable dt = new DataTable();
dt = DBHelper.ExecQuery();
this.txtId.Text = dt.Rows[0]["StuID"].ToString();
this.txtName.Text = dt.Rows[0]["StuName"].ToString();
this.txtAge.Text = dt.Rows[0]["StuAge"].ToString();
this.cmbPro.SelectedValue = dt.Rows[0]["ProfessionID"].ToString();
//性別處理
if (dt.Rows[0]["StuSex"].ToString().Equals("男"))
this.rbBoy.Checked = true;
else
this.rbGirl.Checked = true;
//愛好處理
string[] arrHobby = dt.Rows[0]["StuHobby"].ToString().Split(',');
foreach (string hobby in arrHobby)
{
foreach (CheckBox ck in this.panel2.Controls)
{
if (ck.Text.Equals(hobby))
ck.Checked = true;
}
}
}
private void FrmEdit_Load(object sender, EventArgs e)
{
BindProfession();
BindDetail();
}
private void btUpdate_Click(object sender, EventArgs e)
{
string sql = "update StudentInfo set StuName=@StuName,StuAge=@StuAge,StuSex=@StuSex,StuHobby=@StuHobby,ProfessionID=@ProfessionID where StuID=@StuID";
DBHelper.PrepareSql(sql);
DBHelper.SetParameter("StuName", this.txtName.Text);
DBHelper.SetParameter("StuAge", this.txtAge.Text);
//性別處理
string sex = "";
if (this.rbBoy.Checked == true) sex = this.rbBoy.Text;
if (this.rbGirl.Checked == true) sex = this.rbGirl.Text;
DBHelper.SetParameter("StuSex", sex);
//愛好處理
string hobby = "";
foreach (CheckBox ck in this.panel2.Controls)
{
if (ck.Checked == true)
{
if (!hobby.Equals(""))
hobby += ",";
hobby += ck.Text;
}
}
DBHelper.SetParameter("StuHobby", hobby);
DBHelper.SetParameter("ProfessionID", this.cmbPro.SelectedValue.ToString());
DBHelper.SetParameter("StuID", this.StuID);
int rowCount = DBHelper.ExecNonQuery();
if (rowCount == 1)
{
MessageBox.Show("修改成功!");
this.Close();
}
else
{
MessageBox.Show("修改失敗!");
}
}
(5)查詢窗體中”新增”和”編輯”按鈕代碼:
private void btAdd_Click(object sender, EventArgs e)
{
FrmAdd frm = new FrmAdd();
//frm.Owner = this;
frm.Show();
}
private void btEdit_Click(object sender, EventArgs e)
{
string stuid = this.dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
FrmEdit frm = new FrmEdit();
frm.StuID = stuid;
frm.Show();
}
二、補充:連接字符串配置
將數據庫連接字符串直接寫在C#代碼中,如果連接字符串需要發生改變,必須在C#代碼中修改,並且重新進行編譯的操作,給軟件實施帶來了麻煩。
解決此問題,可以將數據庫連接字符串存放在配置文件中。
(1)在項目中找到App.config文件,如果沒有此文件可以添加一個應用程序配置文件,在此配置文件的configuration節點內部添加如下配置:
<connectionStrings>
<add name="DefaultConn" connectionString="server=.;database=DBTEST;uid=sa;pwd=123456;"/>
</connectionStrings>
(2)給項目添加引用”System.Configuration”,並且將C#中連接字符串的賦值修改如下:
public static string connStr = ConfigurationManager.ConnectionStrings["DefaultConn"].ConnectionString;