2016-02-11 176 views
-5
protected void Button1_Click(object sender, EventArgs e) 
{ 
    MySqlConnection connection = new MySqlConnection(ConfigurationManager.ConnectionStrings["myconstring"].ConnectionString); 
    connection.Open(); 
    symptons = String.Join(", ", CheckBoxList1.Items.Cast<ListItem>().Where(i => i.Selected).Select(i => i.Value).ToArray()); 
    Label3.Text = symptons; 
    if(symptons!="") 
    { 
     MySqlCommand cmd = new MySqlCommand("select d.dname from disease d inner join diseasesymptom ds on ds.did = d.did inner join symptom s on s.sid = ds.sid where s.sname in (" + symptons + ")", connection); 
     using (MySqlDataAdapter sda = new MySqlDataAdapter()) 
     { 
      cmd.Connection = connection; 
      sda.SelectCommand = cmd; 
      using (DataTable dt = new DataTable()) 
      { 
       sda.Fill(dt); 
       GridView1.DataSource = dt; 
       GridView1.DataBind(); 
      } 
     } 
    } 
    else 
    { 
     Label2.Text = "select at least one symptom"; 
    }  
} 

我知道我對我自己的代碼排序進行SQL注入那麼,如何防止這種情況, 基本上有3個表:有沒有更有效的方法來寫這個SQL代碼?

  1. disease_table [欄=(disease_id,disease_name)
  2. symptom_table [列=](symptom_id,symptom_name)
  3. disease_symptom [列=](disease_id,symptom_id)

有一個複選框列表我的網頁上有症狀,其中文本=發燒,值=「發燒」 ..等等這樣做的理由是,用戶可以選擇任意數量的複選框,並在條款不接受參數

+4

**警告**您的代碼極易遭受SQL注入攻擊! –

+0

這就是我說的我該如何改進它,並實現上述結果..人們應該在投票前充分閱讀問題 – panman

+0

也許他們投下因爲你沒有閱讀谷歌的第一頁[「如何避免SQL注射在C#「](https://www.google.com.mx/search?q=how+to+avoid+sql+injection+in+c%23&ie=utf-8&oe=utf-8&gws_rd=cr&ei=ita8Vq- yE4S1-QHcxKfwDQ) –

回答

0

相反到評論中的建議,你不應該需要一個存儲過程來防止SQL注入。您可以使用parameterized queries來獲取dothat。

下面的代碼應該做的工作:

MySqlCommand cmd = new MySqlCommand(); 
cmd.Connection = connection; 

List<string> names = new List<string>(); 
for (int i = 0; i < symptons.Length; i++) 
{ 
    names.Add("@Param_" + i); 
    cmd.Parameters.Add(new MySqlParameter("@Param_" + i, symptons[i])); 
} 
cmd.CommandText = "select d.dname from disease d inner join diseasesymptom ds on ds.did = d.did inner join symptom s on s.sid = ds.sid where s.sname in (" + string.Join(",", names) + ")"; 

基本上你不注射的價值,但注入用於查詢的參數來代替。參數名稱在您的代碼中生成,因此不能混淆。在執行查詢之前,驅動程序對參數的值進行了消毒,所以這些值不能與任何一個混淆。

相關問題