2016-12-17 52 views
-4

我添加了一個文本框和一個按鈕下面爲什麼這個查詢不起作用?

<asp:Label ID="Label1" runat="server" Text="Email'e Göre Silin"></asp:Label> 

     <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> 
     <br /> 
     <br /> 
     <asp:Button ID="Button1" runat="server" Text="Sil" /> 

,但我的查詢是不是這些工作。

SqlConnection con = new SqlConnection("Data Source=DESKTOP-VQUBBVP\\SQLEXPRESS; initial catalog=UgurBocegiDatabase; Integrated Security=True"); 
      con.Open(); 
      SqlCommand cmd = new SqlCommand("delete from tblMessage where Email = '"+TextBox1.Text+ "' ", con); 
      cmd.ExecuteNonQuery(); 

我試着添加下面的.tostring方法,但它沒有再次工作。

SqlCommand cmd = new SqlCommand("delete from tblMessage where Email = '"+TextBox1.Text.ToString()+ "' ", con); 

和查詢SQL Server中的作用類似於下面

delete from tblMessage where Email = 'gs213' 

是什麼問題?

+4

**警告**您的代碼非常容易受到sql注入攻擊 –

+0

永遠不要在家裏做這個,孩子。 – TigOldBitties

+2

閱讀[問]並詳細說明「不起作用」。 – CodeCaster

回答

0

這會工作。

而不是字符串連接,您可以使用下面的參數。

using (SqlConnection connection = 
        new SqlConnection(ConfigurationManager.ConnectionStrings["DEFAULT"].ConnectionString)) 
      { 
       var command = new SqlCommand("delete from tblMessage where email = @email", connection); 
       command.Parameters.Add(new SqlParameter("email", SqlDbType.VarChar) 
       { 
        Value = TextBox1.Text 
       }); 
       connection.Open(); 
       command.ExecuteNonQuery(); 
      } 
+0

嘗試過,沒有@ – Khatibzadeh