简体   繁体   English

如何检查C#中数据库表中是否存在ID?

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

I am trying to delete entries by ID. 我试图通过ID删除条目。 I want to notify user that ID they try to delete doesn't exist. 我想通知用户他们尝试删除的ID不存在。 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? 我必须使用SQL字符串吗?

I am using MS Access 2007 and this is how I delete item: 我正在使用MS Access 2007,这是我删除项目的方式:

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();
}

In VBA code, you could use the DCount() function. 在VBA代码中,您可以使用DCount()函数。

You can also just delete the records with a SQL statement and inform the user after the fact; 您也可以使用SQL语句删除记录,并在事后通知用户; 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. 在ADO.NET中,您可以通过检查ExecuteNonQuery的返回值来遵循相同的方法。 For example, you could declare your function as bool TryDeleteData(string SQL) and do something like 例如,您可以将您的函数声明为bool TryDeleteData(string SQL)并执行类似的操作

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

You could use the DCount function of VBA: 您可以使用VBA的DCount功能:

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

If this is 0 then you know the record doesn't exist and can inform the user. 如果这是0那么您知道该记录不存在并且可以通知用户。

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. 你的问题不够明确,所以我猜你想做的是执行DELETE查询,然后返回是否删除了记录。 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 如果请求的ID不存在,则返回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 (ie a scalar-value). 此查询将生成单列单行结果集(即标量值)。 The value is going to be either 1 or 0 (assuming only one entry may have the same id). 该值将为1或0(假设只有一个条目可能具有相同的id)。 If the count is 0 the entry does not exist. 如果计数为0,则该条目不存在。

PS The way you are executing the query you're opening yourself to SQL injection attacks. PS您执行查询的方式是打开SQL注入攻击。 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! 基本上,有人可以给你以下DataID: 0 OR 1 = 1并猜测会发生什么 - 所有PersonalData记录都将被删除!

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. 或者至少,绝对确保在将用户输入连接到查询文本之前清理并验证用户输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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