首先,定義相關的變數
Dim txtSQL As String Dim msgText As String Dim mrc As ADODB.Recordset
1.定義txtSQL
是用來儲存執行到的SQL語句
2.定義msgText使用來返回查詢狀態,查詢出來的結果是失敗了,還是成功了
3.定義mrc為一個記錄集用來儲存結果。
其次,驗證資料的合法性
1.利用For Each遍曆查詢控制項,判斷是否輸入Null 字元
Dim Ctl As Control For Each Ctl In Me.Controls If TypeOf Ctl Is TextBox Or TypeOf Ctl Is ComboBox Then If Len(Ctl) = 0 Then Ctl.SetFocus MsgBox Ctl.Tag + "未錄入!", vbOKOnly + vbCritical, "提示" Exit Sub End If End If Next
2.判斷卡號等是否輸入數字
If Not IsNumeric(txtCardno.Text) Then MsgBox "輸入的資訊不合法", vbOKOnly + vbExclamation, "卡號" txtCardno.Text = "" txtCardno.SetFocus Exit Function End If
第三,判斷輸入的資料(卡號)是否重複
txtSQL = "select * from student_info where cardno= '" & Trim$(txtCardno.Text) & "'" Set mrc = ExecuteSQL(txtSQL, msgText) If mrc.EOF = False Then MsgBox "卡號重複,請輸入新的卡號", vbOKOnly + vbExclamation, "卡號" mrc.Close txtCardno.SetFocus
第四,向資料庫添加資料,跟學生管理資訊系統直接用mrc.Addnew直接添加不同,下面是用sql語句添加資料。這樣大大減少了代碼的冗餘度。
txtSQL = "Insert into student_info(studentname,sex,studentno,class,grade,cardno,comment,status,sum,department)" & _ " values ('" & txtStudentname.Text & "','" & comboSex.Text & "','" & txtStudentno.Text & _ "','" & txtClass.Text & "','" & txtGrade.Text & "','" & txtCardno.Text & "','" & _ txtComment.Text & " ','" & comboStatu.Text & "','" & txtSum.Text & "','" & txtDepartment.Text & "')" ExecuteSQL txtSQL, msgText mrc.Close MsgBox "註冊成功!", vbOKOnly + vbExclamation Unload Me