0

我有一个示例网站,您可以在其中输入您的电子邮件地址,并将其插入 MS SQL 数据库。在下一页上,GridView 显示来自数据库的列表。现在我需要添加一个删除地址的函数,但它必须验证该地址当前是否为

public partial class Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label1.Text = GetLastWriteTime(Request.PhysicalPath).ToString();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        string data = DateTime.Now.ToLongDateString() + "," + DateTime.Now.ToLongTimeString() + ": ";

        SqlDataSource1.InsertCommand = "INSERT INTO ListaAdresow (Email) Values('" + TextBox1.Text + "')";

        try
        {
            SqlDataSource1.Insert();
            Label2.Text += data + "added into database: " + TextBox1.Text + "<br/>";
            TextBox1.Text = "";
        }
        catch (Exception ex)
        {
            Label2.Text += data + ex.Message;
        }
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        string data = DateTime.Now.ToLongDateString() + "," + DateTime.Now.ToLongTimeString() + ": ";
        SqlDataSource1.DeleteCommand = "DELETE FROM ListaAdresow WHERE Email='" + TextBox1.Text + "'";

        SqlDataSource1.SelectCommand = "SELECT  FROM [ListaAdresow] WHERE Email=" + TextBox1.Text;

        try
        {
                SqlDataSource1.Delete();

                Label2.Text += data + "removed from database: " + TextBox1.Text + "<br/>";
                TextBox1.Text = "";

        }
        catch (Exception ex)
        {
            Label2.Text += data + ex.Message;
        }
    }
}
4

5 回答 5

1

我强烈建议您为所有查询创建存储过程,但例如,从您的 gridview 中,您可以执行以下操作:

if (myGrid.SelectedRows.Count > 0)
{
     int selectedIndex = myGrid.SelectedRows[0].Index;

     // gets the RowID from the first column in the grid
     int rowID = int.Parse(BooksGrid[0, selectedIndex].Value.ToString());

     string sql = "IF EXISTS(SELECT COLUMN FROM Table1 WHERE ID = @rowID)
                    BEGIN 
                      DELETE FROM TABLE1 WHERE ID = @rowID"
                    END;

     }
于 2013-01-14T20:41:06.640 回答
0

要回答您的问题,您可以使用以下内容(未经测试):

SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();

    // Create the SelectCommand using paramaterized queries
        SqlCommand command = new SqlCommand("SELECT * 
                                            FROM ListaAdresow 
                                            WHERE Email = @Email", connection);
    command.Parameters.Add("@Email", SqlDbType.VarChar, 40, TextBox1.Text);

    da.SelectCommand = command;
    da.Fill(dt);

    if (dt.Rows.Count > 0)
    {
        //Row Exists
    }
    else
    {
        //Row Does Not Exist
    }

但是,我重申其他人所说的,DeleteCommand可以自行运行,它将返回受影响记录的数量。

于 2013-01-14T20:40:20.297 回答
0

如果执行删除后可以验证,则数据源的Delete方法返回对数据库影响的总行数。请参阅文档

于 2013-01-14T20:34:49.293 回答
0

尝试使用存储过程并通过参数传递值。因为您可以轻松检查数据库中是否存在数据。它还可以帮助您防止某些 sql 注入。:)

于 2013-05-20T11:51:44.590 回答
0

只需将值放入会话中,并在删除之前使用删除一检查会话值

于 2013-05-20T08:29:20.227 回答