C#.NET 编写后台登录代码

来源:互联网 发布:淘宝刀剑神域武器 编辑:程序博客网 时间:2024/06/07 03:25

  首先 设置前台界面:

       前台界面主要是 两个 TextBox   和一个登录按钮(Button)

       见面设置好以后,我们 双击  按钮 触发事件,进入逻辑代码区进行功能代码的实现;

 

    protected void ImageButton1_Click1(object sender, ImageClickEventArgs e)
    {
        string conn = Convert.ToString(ConfigurationManager.ConnectionStrings["kjwConnectionString"]);  //链接SQL数据库“kjwConnectionString”为你的数据库链接名
        SqlConnection con = new SqlConnection(conn);
        //打开数据库连接
        con.Open();
        string str = "select * from kjw_admin where username='" + TextBox1.Text.Trim() + "' and password='" + TextBox2.Text.Trim() + "'";    //SQL语句将前台中TextBox中的存到数据库的字段中       SqlCommand cmd = new SqlCommand(str, con);
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read())    //判断SQL执行登录是否成功,成功执行下面语句
        {
                      Session["name"] = TextBox1.Text.Trim(); //将用户名保存到SESSION中
                      Response.Redirect("main.html");//成功后页面跳转
         }

       else  //不成功提示登录失败
        {

            Response.Write("<script>alert('用户名或密码错误!')</script>");
        }

        con.Close(); //关闭数据库链接
    }