如上圖所示界面,當我們點擊保存按鈕時將會將表格中的數據保存到數據庫中去,與數據庫進行一個交互
第一步我們就是要獲取到表格中的數據
string pwd = textpwd.Text; //獲得第一次輸入密碼 string agePqd = txtsurepwd.Text; //獲得第二次輸入的密碼 string name = textname.Text; //獲得用戶輸入的名字 int grendID = Change(); //獲得用戶輸入年級 string phone = textphone.Text; //獲得用戶輸入的電話 string Email = txtEmail.Text; //獲得用戶輸入的Email
DateTime birthday = time.Value; //獲得用戶輸入的出生日期 string gender = string.Empty; //獲得用戶輸入的性別 if (boy.Checked) { gender = "1"; } else { gender = "0"; }
因為性別是單選按鈕,所以獲取方式如上面的代碼
為了嚴謹性,我們可以在與數據庫交互之前先進行一道兩次輸入密碼是否正確的判斷
string pwd = textpwd.Text; //獲得第一次輸入密碼 string agePqd = txtsurepwd.Text; //獲得第二次輸入的密碼 if (agePqd.Equals(pwd)) { ................
............... } else { MessageBox.Show("兩次輸入的密碼不一致!", "用戶提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); }
如果判斷正確,那么我們就可以和數據庫進行交互了 和數據庫交互的代碼如下
string str = "data source=.;initial catalog=MySchool;user ID=sa;"; con = new SqlConnection(str); con.Open(); string sql = "insert Student values('" + pwd + "','" + name + "','" + gender + "'," + grendID + ",'" + phone + "','" + birthday + "','" + Email + "');select @@identity"; SqlCommand com = new SqlCommand(sql, con); int count = Convert.ToInt32(com.ExecuteScalar());
以上代碼是將數據庫通道打開,並且將要執行的Sql語句提交到數據庫
添加學生信息完整的代碼如下
string pwd = textpwd.Text; //獲得第一次輸入密碼 string agePqd = txtsurepwd.Text; //獲得第二次輸入的密碼 if (agePqd.Equals(pwd)) { string name = textname.Text; //獲得用戶輸入的名字 int grendID = Change(); //獲得用戶輸入年級 string phone = textphone.Text; //獲得用戶輸入的電話 string Email = txtEmail.Text; //獲得用戶輸入的Email DateTime birthday = time.Value; //獲得用戶輸入的出生日期 string gender = string.Empty; //獲得用戶輸入的性別 if (boy.Checked) { gender = "1"; } else { gender = "0"; } SqlConnection con = null; try { string str = "data source=.;initial catalog=MySchool;user ID=sa;"; con = new SqlConnection(str); con.Open(); string sql = "insert Student values('" + pwd + "','" + name + "','" + gender + "'," + grendID + ",'" + phone + "','" + birthday + "','" + Email + "');select @@identity"; SqlCommand com = new SqlCommand(sql, con); int count = Convert.ToInt32(com.ExecuteScalar()); if (count > 0) { DialogResult result = MessageBox.Show("添加成功!", "用戶提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); txtstudentnumber.Text = count.ToString(); if (result == DialogResult.Yes) { this.Close(); } } } catch (Exception) { MessageBox.Show("添加失敗!", "用戶提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); } finally { if (con != null) { con.Close(); } } } else { MessageBox.Show("兩次輸入的密碼不一致!", "用戶提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); }