<%@ Page Language="C#" AutoEventWireup="true" CodeFile="LoginTest.aspx.cs" Inherits="LoginTest" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>参数化提交SQL语句和拼接SQL语句安全性分析 SQL注入 简单对比分析</title> </head> <body> <form id="form1" runat="server"> <div> 用户名:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> <br /> <br /> 密码:<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br /> <br /> <br /> <asp:Button ID="Button1" runat="server" Text="SQL传递参数" OnClick="Button1_Click" /> <asp:Button ID="Button2" runat="server" Text="SQL拼接语句" OnClick="Button2_Click" /> </div> </form> </body> </html>
using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using MSCL; public partial class LoginTest : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //本文仅对 参数化提交SQL语句和拼接SQL语句安全性分析 SQL注入 简单对比分析 //至于各位在程序中 进行SQL危险字符检测和过滤 不在此讨论范围 } protected void Button1_Click(object sender, EventArgs e) { string UserName = TextBox1.Text.Trim(); string Pwd = TextBox2.Text.Trim(); //实例化Connection对象 SqlConnection connection = new SqlConnection("server=localhost;database=demo;uid=sa;pwd=smile"); connection.Open(); //实例化Command对象 SqlCommand command = new SqlCommand("SELECT COUNT(*) FROM USERINFO WHERE USERNAME=@USERNAME AND UPWD=@UPWD", connection); //第一种添加查询参数的例子 SqlParameter para1 = new SqlParameter("@USERNAME", SqlDbType.NVarChar, 50); para1.Value = UserName; command.Parameters.Add(para1);//添加参数 SqlParameter para2 = new SqlParameter("@UPWD", SqlDbType.NVarChar, 50); para2.Value = Pwd; command.Parameters.Add(para2);//添加参数 try { int i = Convert.ToInt32(command.ExecuteScalar()); if (i > 0) { Response.Write("成功"); } else { Response.Write("失败"); } } catch { } finally { connection.Close(); } /* SqlParameter[] parameters ={ new SqlParameter("@USERNAME",SqlDbType.NVarChar,50), new SqlParameter("@UPWD",SqlDbType.NVarChar,50)}; parameters[0].Value = UserName; parameters[1].Value = Pwd; string sql = "SELECT COUNT(*) FROM USERINFO WHERE USERNAME=@USERNAME AND UPWD=@UPWD"; int i = Convert.ToInt32(MSCL.SqlHelper.GetSingle(sql, parameters)); if (i > 0) { Response.Write("成功"); } else { Response.Write("失败"); } */ } protected void Button2_Click(object sender, EventArgs e) { string UserName = TextBox1.Text.Trim(); //随便输入 string Pwd = TextBox2.Text.Trim(); //典型SQL登陆注入 输入 a' or '1'='1 object obj = MSCL.SqlHelper.GetSingle("SELECT COUNT(*) FROM USERINFO WHERE USERNAME='" + UserName + "' AND UPWD='" + Pwd + "' "); if (Convert.ToInt32(obj) > 0) { Response.Write("成功"); } else { Response.Write("失败"); } } }