如何在VB.NET中调用存储过程并根据用户角色跳转对应窗体
解决方案
1. 修改SQL存储过程
先扩展存储过程,新增输出参数用于返回用户角色,同时优化验证逻辑,一次查询完成验证与角色获取:
ALTER PROCEDURE [dbo].[sp_selectusers] @username varchar(50), @password varchar(50), @result int OUTPUT, @role varchar(20) OUTPUT -- 新增角色输出参数 AS BEGIN -- 初始化参数默认值 SET @result = 0 SET @role = NULL -- 验证账号密码并同步获取角色 SELECT @result = 1, @role = role FROM tbl_credentials WHERE username = @username AND password = @password -- 账号密码用精确匹配,无需LIKE(除非有模糊匹配需求) END
2. 修改VB.NET代码
添加角色参数的定义与获取逻辑,完善角色判断分支:
cm = New SqlCommand("sp_selectusers", cn) With cm .CommandType = CommandType.StoredProcedure .Parameters.AddWithValue("@username", TextBox1.Text) .Parameters.AddWithValue("@password", TextBox2.Text) -- 注册验证结果输出参数 .Parameters.Add("@result", SqlDbType.Int).Direction = ParameterDirection.Output -- 注册角色输出参数 .Parameters.Add("@role", SqlDbType.VarChar, 20).Direction = ParameterDirection.Output .ExecuteNonQuery() -- 无结果集返回,用ExecuteNonQuery更合适 Dim verifyResult As Integer = CInt(.Parameters("@result").Value) If verifyResult = 1 Then Dim userRole As String = .Parameters("@role").Value.ToString().Trim() MsgBox("Welcome " & TextBox1.Text, MsgBoxStyle.Information) -- 根据角色跳转对应窗体 If userRole.Equals("ADMIN", StringComparison.OrdinalIgnoreCase) Then Me.Hide() Form_Admin.Show() ElseIf userRole.Equals("EMPLOYEE", StringComparison.OrdinalIgnoreCase) Then Me.Hide() Form_Employee.Show() Else MsgBox("未知角色,请联系管理员", MsgBoxStyle.Exclamation) End If Else MsgBox("账号不存在或密码错误", MsgBoxStyle.Critical) End If End With
额外注意事项
- 确保
tbl_credentials表存在role字段,类型为varchar/nvarchar - 禁止明文存储密码,建议使用SHA256等哈希算法加密后存储
- 数据库连接建议用
Using语句自动释放资源,避免连接泄漏:Using cn As New SqlConnection("你的数据库连接字符串") cn.Open() Using cm As New SqlCommand("sp_selectusers", cn) ' 命令逻辑写在这里 End Using End Using
内容的提问来源于stack exchange,提问作者Gerry
相关产品推荐
相关产品推荐

