删除数据库中的行

时间:2018-07-17 16:44:56

标签: c# sql-server winforms

我有以下代码,但是我似乎无法操纵它以所需的方式工作。我想让命令在数据库中搜索与facebook匹配的数据库中的第一项并删除该行。

textbox2.text

1 个答案:

答案 0 :(得分:1)

有很多方法可以完成您想做的事情。这是一种方法:

private readonly string SqlConnectionString = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\DillPickle\Documents\Data.mdf;Integrated Security=True;Connect Timeout=30";
private readonly string SqlDeleteQuery = "DELETE FROM ACCNT WHERE ACCNTNUM=@accountNumber";

private void button4_Click(object sender, EventArgs e)
{
    try
    {
        using (var sqlConnection = new SqlConnection(SqlConnectionString))
        using (var sqlCommand = sqlConnection.CreateCommand())
        {
            sqlConnection.Open();

            sqlCommand.CommandText = SqlDeleteQuery;
            sqlCommand.Parameters.AddWithValue("@accountNumber", textBox2.Text);

            sqlCommand.ExecuteNonQuery();
        }
    }  
    catch (Exception ex)
    {
        // Do something with the exception, like log it...
    }
}