首页 > 代码库 > 参数化查询(简单举例)

参数化查询(简单举例)

  这几天在查一些有关SQL语句防注入的资料,敲敲改改总算弄好了,不多说,贴代码

string str = @"server=LAPTOP-CM9CUARS;Integrated Security=SSPI;database=Space;";
            using (SqlConnection Conn = new SqlConnection(str))
            {
                Conn.Open(); //打开数据库 
                try
                {
                    using (SqlCommand Cmd = Conn.CreateCommand())
                    {
                        Cmd.CommandText = "select * from tabUsers where ID=@ID and hspwd=@hspwd";
                        Cmd.Parameters.Add(new SqlParameter("@ID", ID));
                        Cmd.Parameters.Add(new SqlParameter("@hspwd", hspwd1));
                        int count = Convert.ToInt32(Cmd.ExecuteScalar());

                        if (count > 0)
                        { 
                            Session["ID1"] = ID;
                            string sql = "select*from tabUsers where id=‘" + ID + "";
                            string name = Class.Search(sql);
                            Session["name"] = name;
                            Response.Write("<script>alert(‘登录成功!‘);location=‘Space.aspx‘</script>");
                        }
                        else
                            Response.Write("<script>alert(‘登录失败,请正确填写账号、密码!‘)</script>");
                    }
                }

参数化查询(简单举例)