ExecuteScalar.Connection属性尚未初始化

时间:2019-10-01 01:53:46

标签: .net vb.net winforms

    Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
        If txtUsername.Text = Nothing Or txtPassword.Text = Nothing Then
            MsgBox("Enter Credential", MsgBoxStyle.Exclamation)
        End If
            If connection.State = ConnectionState.Closed Then
            connection.Open()
        End If
        Dim cmd As New OleDbCommand("select count (*) from Admin where username = ? and password = ?, connection")
        cmd.Parameters.AddWithValue("@1", OleDbType.VarChar).Value = txtPassword.Text
        cmd.Parameters.AddWithValue("@2", OleDbType.VarChar).Value = txtUsername.Text
        Dim count = Convert.ToInt32(cmd.ExecuteScalar())
        If (count > 0) Then
            MsgBox("Login Succeed", MsgBoxStyle.Information)
        Else
            MsgBox("Account not found check credentials", MsgBoxStyle.Critical)
        End If
    End Sub
End Class

任何人都可以帮助我编写此代码... 这是用于登录表单

1 个答案:

答案 0 :(得分:1)

如果验证失败,您将要退出Sub。 Return语句完成了此操作。

您将要在Using块之外声明计数。您将在评估计数之后显示消息框,并且我们不希望用户响应消息框时挂起连接,因此我们在Using块之外进行评估。

使数据库对象保持本地状态,以便您可以控制何时关闭和处理它们。即使有错误,Using...End Using块也会完成此操作。

按照@MathieuGuindon在其评论中所说的那样纠正您的OleDbCommand构造函数。

我很高兴看到正在使用的参数,以至于我不敢抱怨,但是首选.Add方法。 http://www.dbdelta.com/addwithvalue-is-evil/https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/ 还有一个: https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications 这是另一个 https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html实际上,您正在混合使用这两种方法。 .AddWithValue第二个参数期望的值不是OleDbType。它是Object类型的,因此它不会产生编译错误,但是当它到达数据库时会崩溃。

在.Execute连接是宝贵的资源之前,请勿打开连接。

最后,永远不要将密码存储为纯文本。我将留给您研究盐析和哈希处理以保护密码。

Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
    If String.IsNullOrWhiteSpace(txtUsername.Text) OrElse String.IsNullOrWhiteSpace) txtPassword.Text) Then
        MsgBox("Enter Credential", MsgBoxStyle.Exclamation)
        Return
    End If
    Dim count As Integer
    Using connection As New OleDbConnection("Your connection string")
        Using cmd As New OleDbCommand("select count (*) from Admin where username = ? and password = ?", connection)
            cmd.Parameters.Add("@1", OleDbType.VarChar).Value = txtPassword.Text
            cmd.Parameters.Add("@2", OleDbType.VarChar).Value = txtUsername.Text
            connection.Open()
            count = Convert.ToInt32(cmd.ExecuteScalar())
        End Using
    End Using 'Closes and Disposes the connection
    If count > 0 Then
        MessageBox.Show("Login Succeed", "Login", MessageBoxButtons.OK, MessageBoxIcon.Information)
    Else
        MessageBox.Show("Account not found check credentials", "Login", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End If

End Sub