C#实现登录功能(连接SQLServer数据库)

本例使用C#实现一个简单的登录功能,分为用户和管理员两个角色登录。

效果图:

 

 

 

 核心代码

login.cs

        private void button1_Click(object sender, EventArgs e)
        {
            if (textBox1.Text != "" && textBox2.Text != "")
            {
                loginCheck();
            }
            else
            {
                MessageBox.Show("账号和密码不能为空");
            }
        }
        //登录验证
        public void loginCheck()
        {
            if (userName.Checked == true)
            {
                Dao dao = new Dao();//实例化数据库对象
                string sql="select * from t_user where id='"+textBox1.Text+"' and pwd='"+textBox2.Text+"'";
                IDataReader dc = dao.read(sql);
                if (dc.Read())
                {
                    Data.UID = dc["id"].ToString();
                    Data.UName = dc["name"].ToString();

                    MessageBox.Show("用户角色登录成功");
                    user1 user = new user1();
                    this.Hide();
                    user.ShowDialog();
                    this.Show();
                }
                else
                {
                    MessageBox.Show("密码错误,登录失败");
                }
                dao.DaoClose();
            }

            if (adminName.Checked == true)
            {
                Dao dao = new Dao();//实例化数据库对象
                string sql = "select * from t_admin where id='" + textBox1.Text + "' and pwd='" + textBox2.Text + "'";
                IDataReader dc = dao.read(sql);
                if (dc.Read())
                {
                    MessageBox.Show("管理员角色登录成功");
                    admin1 admin = new admin1();
                    this.Hide();
                    admin.ShowDialog();
                    this.Show();
                }
                else
                {
                    MessageBox.Show("密码错误,登录失败");
                }
                dao.DaoClose();
            }
        }

Data.cs

class Data
    {
        public static string UID = "", UName = "";//登录用户的id和姓名
    }

Dao.cs

class Dao
    {
        SqlConnection sc;
        public SqlConnection connect()
        {
            string str = @"Data Source=LAPTOP-H45ALQK7;Initial Catalog=BookDB;Integrated Security=True";//配置数据库
            sc = new SqlConnection(str);//创建数据库连接对象
            sc.Open();//打开数据库
            return sc;//返回数据库连接对象
        }
        public SqlCommand command(string sql)
        {
            SqlCommand cmd = new SqlCommand(sql, connect());
            return cmd;
        }
        public int Execute(string sql)//更新操作
        {
            return command(sql).ExecuteNonQuery();
        }
        public SqlDataReader read(string sql)//读取操作
        {
            return command(sql).ExecuteReader();
        }
        public void DaoClose()
        {
            sc.Close();//关闭数据库
        }
    }
原文地址:https://www.cnblogs.com/zyj3955/p/15487274.html