为什么这个查询不起作用?

时间:2016-12-17 13:38:12

标签: sql asp.net .net

我添加了一个文本框和一个按钮,如下所示

<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'

问题是什么?

1 个答案:

答案 0 :(得分: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();
            }