c# 登录 防止sql注入 mysql数据库

利用参数化 防止SQL注入

    public string serachName(string name)
        {
            
            string result = "";
            try
            {
                conn.Open();
                string sqlstr = "select * from student where name like @serach_name";
                SqlParameter namevalue = new SqlParameter("@serach_name", name);
                MySqlCommand cmd = new MySqlCommand(sqlstr, conn);
                cmd.Parameters.AddRange(new MySqlParameter[] { new MySqlParameter("@serach_name", MySqlDbType.String) { Value = "%" + name + "%" } });
                MySqlDataReader reader = cmd.ExecuteReader();
               
                while(reader.Read())
                {
                    int sno = reader.GetInt32(reader.GetOrdinal("sno"));
                    string tempname = reader.GetString(reader.GetOrdinal("name"));
                    string sex = reader.GetString(reader.GetOrdinal("sex"));
                    int age = reader.GetInt32(reader.GetOrdinal("age"));
                    result += sno + " " + tempname + " " + sex + " " + age + "<br>";
                } 
            }catch(Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                conn.Close();
            }
            return result;
        }

 stirng nn="aa or 1=1";
"select * from tb where t1='"+nn+"'";


//防注入
"select * from tb where t1=@N";
cmd.Parameters.Add(new SqlParameter(@N,aa or 1=1));

 

第一句

select * from tb where t1='aa' or 1=1

第二句

select * from tb where t1='aa' or 1=1'

posted @ 2018-10-04 11:14  chenzquan  阅读(2797)  评论(0编辑  收藏  举报