sql-server - VB.Net 登录表单使用带有重定向到不同表单的角色的 SQL Server
问题描述
我目前正在开发一个以 VB.net 和 SQL Server 为数据库的员工管理系统。
这是我当前的数据库表的样子:
这是登录表单的样子:
我想要这个登录表单和那个单一的登录按钮来适应管理员和员工角色。每个角色都有不同的形式。这是我当前的代码的样子:
Private Sub logIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonLogin.Click
Dim connectionLogin As New SqlConnection(connectionstring)
sqlLogin = "SELECT (1000) [Login]
,[Password]
,[Role]
FROM [RestaurantDatabase].[dbo].[Login] where Login ='" & txtUsername.Text & "'"
connectionLogin.Open()
sAdapterLogin = New SqlDataAdapter(sqlLogin, connectionLogin)
SDsLogin = New DataSet()
sAdapterLogin.Fill(SDsLogin, "login")
sTableLogin = SDsLogin.Tables("login")
If sTableLogin.Rows.Count = 0 Then
MessageBox.Show("Wrong Username", "Unauthorized", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Else
If sTableLogin.Rows.Item(0).Item("Password") = txtPassword.Text Then
formTasks.Show()
Else
MessageBox.Show("Wrong Password entered", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop)
End If
End If
End Sub
我该怎么做呢?我当前的代码没有考虑角色。管理员和员工都被重定向到同一个表单。
解决方案
和使用非托管代码之类Connection
的数据库对象。这些类的作者提供了一种释放非托管资源的方法。我们必须调用这些对象。幸运的是,vb.net 提供了块来为我们解决这个问题。该块也关闭了. 要在一个块中包含多个对象,请用逗号分隔它们。Command
DataReader
Dispose
Dispose
Using...End Using
Using
Connection
Using
将表的名称与字段的名称相同并不是一个好习惯。(登录)
永远不要连接字符串来构建 sql 命令文本。这让您对 sql 注入敞开大门。这意味着用户可以在文本框中插入可执行代码并损坏您的数据库。始终使用参数。Sql Server 不将参数值视为可执行文件。
如果选择角色并将用户和密码传递给 Sql Server,则只需要检索一条数据。ExecuteScalar
通过返回结果集第一行的第一列来做到这一点。您不需要DataAdapter
or DataSet
。
只有在连接关闭后,我们才检查有效性并根据角色的值进行操作。
Private Sub logIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonLogin.Click
Dim SqlLogin = "SELECT [Role]
FROM [RestaurantDatabase].[dbo].[Login]
Where [Login] = @User And [Password] = @Password;"
Dim role As String = ""
Using connectionLogin As New SqlConnection(connectionstring),
cmd As New SqlCommand(SqlLogin, connectionLogin)
cmd.Parameters.Add("@User", SqlDbType.VarChar).Value = txtUsername.Text
cmd.Parameters.Add("@Password", SqlDbType.VarChar).Value = txtPassword.Text
connectionLogin.Open()
role = CStr(cmd.ExecuteScalar)
End Using 'closed the Connection and disposes the Connection and Command
If String.IsNullOrEmpty(role) Then
MessageBox.Show("Invalid credentials", "Unauthorized", MessageBoxButtons.OK, MessageBoxIcon.Stop)
Else
If role = "Admin" Then
'Show the admin form
Else
'Show the employee form
End If
End If
End Sub
我在这里没有处理这个问题,但密码永远不应该以纯文本形式存储。这是为了保护您的用户和数据库。密码应该加盐和散列。
推荐阅读
- javascript - React Component 不会以父组件的给定状态呈现
- django - 我提出了两个验证错误,但如果其中任何一个被触发,它总是给我相同的验证错误输出
- kotlin - 如何在 tornadofx imageview 中显示新图像?
- python - (imutils)PackagesNotFoundError:当前频道不提供以下软件包:
- cuda - 如何在 CUDA 中定义全局常量?
- asp.net-mvc - 关于 ASP.NET MVC 中路由的一些基本问题
- python - 尝试根据限制选择行时出现问题?
- python - 我正在使用 K-NNs 分类进行文本分析
- javascript - React Typescript:无法将组件分配给元素
- servicestack - 将 JwtAuthProviderReader 与 ServiceStack 和 AWS Cognito 一起使用