首页 > 解决方案 > VB.NET 数据表行

问题描述

我正在尝试制作登录表单。

我在我的服务器上创建了一个数据库并创建了行用户名和密码。然后我创建了一个root用户,密码为root。

但我在检查用户名和密码是否正确时遇到问题,我不知道如何给他 2 行。

Dim conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
Dim sda = New SqlDataAdapter("select count(*) from tblLogin where username ='" + txtUsername.Text + "' and password='" + txtUserPwd.Text + "'", conn)
Dim dt = New DataTable()
sda.Fill(dt)
If (dt.Rows().ToString() = "1") Then
    MsgBox("Logged-in successfully")
Else
    MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If

桌子:

桌子

标签: sql-serverdatabasevb.netlogin

解决方案


在线评论和解释。

Private Sub VerifyLogin()
        'For the Return Value of the command
        Dim RetVal As Integer
        ' A Using...End Using will ensure that you connectionis closed and disposed event
        'it there is an error.
        Using conn = New SqlConnection("Data Source=SRV-SQL;Initial Catalog=prova;User ID=user;Password=user")
            'You don't need a DataAdapter, just a command
            'USE PARAMETERS. Yes, I am yelling :-) Even if you are the only user
            'it will save you headaches with syntax.
            Using cmd = New SqlCommand("select count(*) from tblLogin where username = @UserName and password= @Password;", conn)
                cmd.Parameters.Add("@UserName", SqlDbType.VarChar).Value = txtUsername.Text
                cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = txtUserPwd.Text
                'You are only returning one row
                'ExecuteScalar returns the value in the first column of the 
                'first row of the the data
                conn.Open()
                RetVal = CInt(cmd.ExecuteScalar)
            End Using
        End Using
        'No need to convert to a string just compare the Integer
        If RetVal = 1 Then
            MsgBox("Logged-in successfully")
        Else
            MessageBox.Show("The username or the password is wrong!", "Warning!", MessageBoxButtons.OK, MessageBoxIcon.Error)
        End If
End Sub

推荐阅读