验证代码在数据库中存储空数据

时间:2013-12-18 09:19:56

标签: .net vb.net

我用VB.NET编写了一个简单的验证代码。此代码将EMPTY数据存储在数据库表中。如何避免这种情况,以及在else if语句后我写的代码是什么?即电话没有验证后。

这是下面的代码:

 Protected Sub Button1_Click(sender As Object, e As System.EventArgs) Handles Button1.Click
        If Len(Trim(txtName.Text)) = 0 Then
            MsgBox("Enter Name", MsgBoxStyle.Critical, "Error")
            txtName.Focus()
        ElseIf Len(Trim(txtAge.Text)) = 0 Then
            MsgBox("Enter Age", MsgBoxStyle.Critical, "Error")
            txtAge.Focus()
        ElseIf Len(Trim(txtPhone.Text)) = 0 Then
            MsgBox("Enter Phone", MsgBoxStyle.Critical, "Error")
            txtPhone.Focus()
        Else
            Dim blnFlag As Boolean = False
            MsgBox("Enter the details", MsgBoxStyle.Critical, "Error")
        End If
        Try
            Dim strCommand As String
            strCommand = "Insert into [Validation] ([Name],[Age],[Phone]) VALUES"
            strCommand = strCommand & "('" & Trim(txtName.Text) & "','" & Trim(txtAge.Text) & "','" & Trim(txtPhone.Text) & "')"
            Dim StrConnection As String
            StrConnection = ConfigurationManager.ConnectionStrings("ConnectionString").ToString
            Dim cnValidation As New SqlClient.SqlConnection(StrConnection)
            If (cnValidation.State = ConnectionState.Closed) Then
                cnValidation.Open()
            End If
            Dim cmdEmployee As New SqlClient.SqlCommand(strCommand, cnValidation)
            cmdEmployee.ExecuteNonQuery()
            cnValidation.Close()
            MsgBox("Save Successful", MsgBoxStyle.Information, "Success")
        Catch ex As Exception
            MsgBox("Save failed " & ex.Message, MsgBoxStyle.Critical, "Failed")
        End Try

1 个答案:

答案 0 :(得分:2)

最简单的方法是,在验证失败后从方法返回:

If Len(Trim(txtName.Text)) = 0 Then
    MsgBox("Enter Name", MsgBoxStyle.Critical, "Error")
    txtName.Focus()
    Return
ElseIf Len(Trim(txtAge.Text)) = 0 Then
    MsgBox("Enter Age", MsgBoxStyle.Critical, "Error")
    txtAge.Focus()
    Return
ElseIf Len(Trim(txtPhone.Text)) = 0 Then
    MsgBox("Enter Phone", MsgBoxStyle.Critical, "Error")
    txtPhone.Focus()
    Return
Else
    Dim blnFlag As Boolean = False
    MsgBox("Enter the details", MsgBoxStyle.Critical, "Error")
    Return
End If

然而,"Enter the details"部分尚不清楚。为什么总是显示错误-MessageBox?似乎存在逻辑问题。我今后将忽略这一部分。

这是一个更易读的.NET代码版本:

Dim validName = Not String.IsNullOrWhiteSpace(txtName.Text)
Dim validAge = Not String.IsNullOrWhiteSpace(txtAge.Text)
Dim validPhone = Not String.IsNullOrWhiteSpace(txtPhone.Text)
Dim isValid = validName AndAlso validAge AndAlso validPhone

If Not isValid Then
    If Not validName Then
        MsgBox("Enter Name", MsgBoxStyle.Critical, "Error")
        txtName.Focus()
    ElseIf Not validAge Then
        MsgBox("Enter Age", MsgBoxStyle.Critical, "Error")
        txtAge.Focus()
    ElseIf Not validPhone Then
        MsgBox("Enter Phone", MsgBoxStyle.Critical, "Error")
        txtPhone.Focus()
    End If
    Return ' return from this method '
Else
    ' insert into DB '
    ' .... '
End If

旁注:你应该使用sql-parameters,即使这是一个windows-application。它不仅可以阻止您sql-injection attacks,还可以防止本地化问题(例如datetime):

Try
    Dim newIdenity As Int32 ' determine new ID generated from database '
    Dim strCommand = "Insert into [Validation] ([Name],[Age],[Phone]) VALUES (@Name,@Age,@Phone)"
    Dim StrConnection As String = ConfigurationManager.ConnectionStrings("ConnectionString").ToString
    Using cnValidation = New SqlClient.SqlConnection(StrConnection)
        Using cmdEmployee = New SqlCommand(strCommand, cnValidation)
            cnValidation.Open()
            cmdEmployee.Parameters.AddWithValue("@Name",txtName.Text)
            cmdEmployee.Parameters.AddWithValue("@Age",Int32.Parse(txtAge.Text))
            cmdEmployee.Parameters.AddWithValue("@Phone",txtPhone.Text)
            newIdenity = DirectCast(cmdEmployee.ExecuteScalar(), Int32)
        End Using
    End Using
    MsgBox("Save Successful", MsgBoxStyle.Information, "Success")
Catch ex As Exception
    MsgBox("Save failed " & ex.Message, MsgBoxStyle.Critical, "Failed")
End Try

对于处理非托管资源的所有实现Using,您应该使用IDisposable - 语句,它也会关闭连接,即使出错也是如此。

我还展示了如何从sql-server中的IDENTITY列确定新创建的标识值。

请注意,我已将txtAge.Text解析为Int32,因为我假设数据库中列的类型实际为int。如果不是这种情况,请删除Int32.Parse。通常,您应始终提供正确的类型作为参数。

相关问题