简体   繁体   中英

How do I delete an entire row from a database

How would I delete a row from a sql database, either with stored procedures or without, right now I have tried without, using a button press. This is what I have so far, _memberid has been sent over from a differnt form from the database(For context).

private void btnDelete_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = Lib.SqlConnection;
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "Delete * From Members where MemberId = " + _memberId;
        SqlDataAdapter adapter = new SqlDataAdapter();
        adapter.DeleteCommand = cmd;
        adapter.Fill(MembersDataTable); // Im fairly sure this is incorrect but i used it from old code
        DialogResult = DialogResult.OK;
    }

If you're trying to do a simple ADO.Net-based delete, then it would be somehting like his:

private void DeleteById(int memberId)
{
   // or pull the connString from config somewhere
   const string connectionString = "[your connection string]";

   using (var connection = new SqlConnection(connectionString))
   {
       connection.Open();

       using (var command = new SqlCommand("DELETE FROM Members WHERE MemberId = @memberId", connection))
       {
           command.Parameters.AddWithValue("@memberId", memberId);
           command.ExecuteNonQuery();
       }
   }

Use parameter to prevent SQL injection.

You could use a DataAdapter, but since you aren't using a datatable, it's just easier to do it without like this:

var sql = "DELETE FROM Members WHERE MemberId=@MemberId";
using(var cmd = new SqlCommand(sql, Lib.SqlConnection))
{
  cmd.Connection.Open();
  cmd.Parameters.Add("@MemberId",SqlDbType.Int).Value = _memberId;
  cmd.ExecuteNonQuery();
}

And if you are using Dapper , you can do this:

Lib.SqlConnection.Execute("DELETE FROM Members WHERE MemberId=@MemberId", new {MemberId=_memberId});

If you are still using DataTables, I would highly recommend you look into using this (or something like this) to simplify your database accesses. It'll make CRUD logic on a database a breeze, and your code will me a lot more maintainable because you can get rid of all the odd needs to do casting, boxing/unboxing, and reduce the chances of runtime bugs because of the use of magic strings that happens so often with DataTables (column names). Once you start working with POCO classes, you'll hate having to use DataTables. That said, there are a few places where DataTables are a better solution (unknown data structures, etc), but those are usually pretty rare.

There are essentially three main things I'm seeing...

One

You don't need the * in the query. DELETE affects the whole row, so there's no need to specify columns. So just something like:

DELETE FROM SomeTable WHERE SomeColumn = 123

Two

There's no need for a SqlDataAdapter here, all you need to do is execute the query . For example:

cmd.ExecuteNonQuery();

The "non query" is basically a SQL command which doesn't query data for results. Inserts, updates, and deletes are generally "non queries" in this context. What it would return is simply the number of rows affected, which you can use to double-check that it matches what you expect if necessary.

Three

Don't do this :

cmd.CommandText = "Delete From Members where MemberId = " + _memberId;

This kind of string concatenation leads to SQL injection . While it looks intuitively like you're using _memberId as a query value, technically you're using it as executable code . It's less likely (though not impossible) to be a problem for numeric values, but it's a huge problem for string values because it means the user can send you any string and you'll execute it as code .

Instead, use query parameters . For example, you might do something like this:

cmd.CommandText = "Delete From Members where MemberId = @memberId";
cmd.Parameters.Add("@memberId", SqlDbType.Int);
cmd.Parameters["@memberId"].Value = _memberId;

This tells the database engine itself that the value is a value and not part of the executing query, and the database engine knows how to safely handle values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM