以下是学习笔记:
参考:https://www.bilibili.com/video/BV1LK4y1k7HM?t=2583 感谢朝夕教育
1,UI的点击登录按钮。
目的:把userId传入主窗体的Tag值
/// <summary> /// 登录过程 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnLogin_Click(object sender, EventArgs e) { //1.接收页面输入 string userName = txtUName.Text.Trim(); string userPwd = txtUPwd.Text.Trim(); //2.判断账号 密码 是否为空 if (string.IsNullOrEmpty(userName)) { MsgBoxHelper.MsgErrorShow("账号不能为空!"); txtUName.Focus(); return; } if (string.IsNullOrEmpty(userPwd)) { MsgBoxHelper.MsgErrorShow("密码不能为空!"); txtUPwd.Focus(); return; } UserInfoModel userInfo = new UserInfoModel() { UserName = userName, UserPwd = userPwd }; //3.到数据库里检查存在性 ---成功 否则---失败 UserDAL userDAL = new UserDAL(); int userId = userDAL.Login(userInfo); if (userId > 0) { MsgBoxHelper.MsgBoxShow("登录提示", "登录成功!"); //显示到主页面 FrmMain fMain = new FrmMain(); fMain.Tag = userId; fMain.WindowState = FormWindowState.Maximized; fMain.Show(); this.Hide(); } else { MsgBoxHelper.MsgErrorShow("账号或密码输入有误!"); return; } }
2,DAL的数据访问
/// <summary> /// 登录系统 /// </summary> /// <param name="user"></param> /// <returns></returns> public int Login(UserInfoModel user) { string sql = "select UserId from UserInfos where UserName=@UserName and UserPwd=@UserPwd"; SqlParameter[] paras = { new SqlParameter("@UserName",user.UserName), new SqlParameter("@UserPwd",user.UserPwd) }; object oId = DBHelper.ExecuteScalar(sql, 1, paras); if (oId != null && oId.ToString() != "") { return oId.GetInt(); } else return 0; }
3,数据访问类
/// <summary> /// 执行sql查询,返回第一行第一列的值 /// </summary> /// <param name="sql">sql语句或存储过程</param> /// <param name="cmdType">执行的脚本类型 1:sql语句 2:存储过程</param> /// <param name="parameters">参数列表</param> /// <returns></returns> public static object ExecuteScalar(string sql,int cmdType, params SqlParameter[] parameters) { //params 只能写在一维数组之前,且只能标识参数列表中的最后一个参数 //select @@Identity 返回上一次插入记录时自动产生的ID object result = null;//返回结果 using (SqlConnection conn = new SqlConnection(connStr)) { //执行脚本的对象cmd SqlCommand cmd = BuilderCommand(conn, sql, cmdType, null, parameters); result = cmd.ExecuteScalar();//执行T-SQL并返回第一行第一列的值 cmd.Parameters.Clear(); if (result == null || result == DBNull.Value) { return null; } else { return result; } } }