HelpNeeder
HelpNeeder

Reputation: 6490

How to check if ID exists in database table in C#?

I am trying to delete entries by ID. I want to notify user that ID they try to delete doesn't exist. It doesn't create any problems, but I want to make everything clear.

How to do that? Do I have to use SQL string to do so?

I am using MS Access 2007 and this is how I delete item:

string SQL = "DELETE FROM PersonalData WHERE DataID = " + txtEntryID.Text;

private void DeleteData(string SQL)
{
    // Creating an object allowing me connecting to the database.
    // Using parameters in command will avoid attempts of SQL injection.
    OleDbConnection objOleDbConnection = new OleDbConnection();
    // Creating command object.
    objOleDbConnection.ConnectionString =
        "Provider=Microsoft.ACE.OLEDB.12.0;" +
        "Data Source=" + filePath + ";" +
        "Persist Security Info=False;" +
        "Jet OLEDB:Database Password=" + pass + ";";
    OleDbCommand objOleDbCommand = new OleDbCommand();

    objOleDbCommand.CommandText = SQL;

    // Assigning a connection string to the command.
    objOleDbCommand.Connection = objOleDbConnection;

    try
    {
        // Open database connection.
        objOleDbConnection.Open();
        objOleDbCommand.ExecuteNonQuery();
    }
    catch (Exception ex)
    {
        // Displaying any errors that 
        // might have occured.
        MessageBox.Show("Error: " + ex.Message);
    }
    finally
    {
        // Close the database connection.
        objOleDbConnection.Close();
    }

    // Refreshing state of main window.
    mainWindow.DisplayFileContent(filePath);

    MessageBox.Show("Data was successfully deleted.");

    // Clearing text box field.
    txtEntryID.Clear();
}

Upvotes: 2

Views: 3043

Answers (3)

Mike Dinescu
Mike Dinescu

Reputation: 55760

Your question isn't clear enough, so I'm guessing that what you'd like to do is execute the DELETE query and then return whether records were deleted or not. If that's what you want to do you could do it like this:

DECLARE @deletedID AS INT
SELECT @deletedID = id FROM your_table WHERE id = <the id supplied by user>

DELETE FROM your_table
   WHERE your_table.id = <the id supplied by user>

RETURN @deletedID

If the requested ID does not exist this will return NULL

EDIT

Based on the clarification in your comments, the following query should work just fine:

SELECT COUNT(DataId) as Cnt 
  FROM PersonalData WHERE DataId = <user_specified_id>

This query will produce a single column, single row result set (i.e. a scalar-value). The value is going to be either 1 or 0 (assuming only one entry may have the same id). If the count is 0 the entry does not exist.

P.S. The way you are executing the query you're opening yourself to SQL injection attacks. Basically, someone could give you the following DataID: 0 OR 1 = 1 and guess what's going to happen - all the PersonalData records will be deleted!

A much better approach would be to use prepared statements. Or at the very least, make absolute sure that you sanitize and validate the user input before concatenating it into the query text.

Upvotes: 3

phoog
phoog

Reputation: 43056

In VBA code, you could use the DCount() function.

You can also just delete the records with a SQL statement and inform the user after the fact; from the user's point of view there's no difference:

Dim id As Long

id = GetAnIdFromTheUser()

With CurrentDb
    Do
        .Execute "DELETE FROM [TableName] WHERE ID = " & id
        If .RecordsAffected > 0 Then
            Goto Done
        End If
        MsgBox "That ID doesn't exist; please try another."
        id = GetAnIdFromTheUser()
    Loop
Done:
    .Close
End With

EDIT:

In ADO.NET you can follow the same approach by examining the return value of ExecuteNonQuery. For example, you could declare your function as bool TryDeleteData(string SQL) and do something like

...
if (objOleDbCommand.ExecuteNonQuery() == 0)
    return false;
...

Upvotes: 3

Yuck
Yuck

Reputation: 50855

You could use the DCount function of VBA:

DCount("*", "SomeTable", "ID = 1")

If this is 0 then you know the record doesn't exist and can inform the user.

Upvotes: 3

Related Questions