VB.Net结合SQL Server实现带角色验证、登录跳转不同窗体的方法
代码修改方案
最小改动方案(无需调整原有数据读取逻辑)
你只需要在密码验证通过的分支内,读取返回结果里的Role字段做判断,跳转对应窗体即可,修改部分如下:
If sTableLogin.Rows.Item(0).Item("Password") = txtPassword.Text Then ' 以下为新增角色判断逻辑,请根据你数据库Login表Role字段的实际存储值调整判断条件 Dim userRole = sTableLogin.Rows(0).Item("Role") ' 示例假设Role字段值1代表管理员,0代表普通员工,如存储的是字符串可调整为对应字符串判断 If Convert.ToInt32(userRole) = 1 Then formAdmin.Show() '替换为你项目中实际的管理员窗体类名 Else formStaff.Show() '替换为你项目中实际的员工窗体类名 End If Me.Hide() ' 可选操作:登录成功后隐藏当前登录窗体 Else MessageBox.Show("Wrong Password entered", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop) End If
优化方案(修复SQL注入风险)
原代码直接拼接用户名到SQL语句存在SQL注入漏洞,恶意用户可通过特殊输入窃取、删除数据库数据,建议改用参数化查询,完整代码如下:
Private Sub logIn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonLogin.Click ' 请根据你表中Role字段的实际存储值调整常量取值 Const ROLE_ADMIN As Integer = 1 Const ROLE_STAFF As Integer = 0 ' Using语法会自动释放数据库连接资源,无需手动关闭 Using connectionLogin As New SqlConnection(connectionstring) Dim sqlLogin As String = "SELECT [Password], [Role] FROM [RestaurantDatabase].[dbo].[Login] WHERE Login = @Username" Dim cmd As New SqlCommand(sqlLogin, connectionLogin) ' 参数化传递用户名,彻底避免SQL注入风险 cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim()) connectionLogin.Open() Dim reader As SqlDataReader = cmd.ExecuteReader() If Not reader.HasRows Then MessageBox.Show("用户名错误", "未授权", MessageBoxButtons.OK, MessageBoxIcon.Stop) Else reader.Read() Dim dbPassword = reader("Password").ToString().Trim() If dbPassword = txtPassword.Text.Trim() Then Dim userRole = Convert.ToInt32(reader("Role")) If userRole = ROLE_ADMIN Then formAdmin.Show() '替换为实际管理员窗体名 ElseIf userRole = ROLE_STAFF Then formStaff.Show() '替换为实际员工窗体名 End If Me.Hide() Else MessageBox.Show("输入的密码错误", "错误", MessageBoxButtons.OK, MessageBoxIcon.Stop) End If End If reader.Close() End Using End Sub
注意:如果你的
Role字段存储的是「管理员」「员工」类的字符串值,将代码中的数值判断调整为字符串判断即可。
内容的提问来源于stack exchange,提问作者Andre' Bella
相关产品推荐
相关产品推荐

