2.5登录用户验证功能设计

GIF效果图

2.5.gif

功能阐述及后台数据库表结构

1.实现登陆信息到数据库实现验证
CREATE TABLE [dbo].[USERS](
[ID] [int] NOT NULL,
[NAME] varchar NULL,
[PASSWORD] varchar NULL,
[PHONE] varchar NULL,

查询数据库流程

String connStr = "Data Source=.;Initial Catalog=SuperMarketSales;Integrated Security=True";
SqlConnection sqlConn = new SqlConnection(connStr);
try
{
sqlConn.Open();

            String sqlStr = "";

            if (this.cbb_UserType.Text == "收银员")
            {
                // 注意USER是SQL Server关键字,表名不能命名为USER,而应当用USERS
                sqlStr = "select * from USERS where ID=@id and PASSWORD=@pwd";
            }
            else
            {
                sqlStr = "select * from ADMIN where ID=@id and PASSWORD=@pwd";
            }

            SqlCommand cmd = new SqlCommand(sqlStr, sqlConn);

            // 注意是用用户ID登录,而不是用户名,用户名可能会重复
            cmd.Parameters.Add(new SqlParameter("@id", this.tb_User.Text.Trim()));
            cmd.Parameters.Add(new SqlParameter("@pwd", this.tb_Password.Text.Trim()));

            SqlDataReader dr = cmd.ExecuteReader();

            // 如果从数据库中查询到记录,则表示可以登录
            if (dr.HasRows)
            {
                dr.Read();
                UserInfo.userId = int.Parse(dr["ID"].ToString());
                UserInfo.userName = dr["NAME"].ToString();
                UserInfo.userPwd = dr["PASSWORD"].ToString();
                UserInfo.userPhone = dr["PHONE"].ToString();
                UserInfo.userType = this.cbb_UserType.Text;

                MessageBox.Show(UserInfo.userType + "登录成功");

                if (UserInfo.userType == "收银员")
                {
                    // 显示收银员主界面
                    MainFormUser formUser = new MainFormUser();
                    formUser.Show();

                    // 隐藏登录界面
                    this.Hide();
                }

                if (UserInfo.userType == "库管员")
                {
                    // 显示库管员主界面
                    MainFormAdmin formAdmin = new MainFormAdmin();
                    formAdmin.Show();

                    // 隐藏登录界面
                    this.Hide();
                }
            }
            else
            {
                MessageBox.Show("用户名或密码错误", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        catch (Exception exp)
        {
            MessageBox.Show("数据库连接失败");
        }
        finally
        {
            sqlConn.Close();
        }

你可能感兴趣的:(2.5登录用户验证功能设计)