简体   繁体   English

C#SQLite删除不起作用

[英]C# SQLite delete does not work

I have this helper function: 我有这个辅助功能:

public bool Delete(String tableName, String where)
    {
        Boolean returnCode = true;
        try
        {
            this.ExecuteNonQuery(String.Format("delete from {0} where {1};", tableName, where));                
        }
        catch (Exception fail)
        {
            MessageBox.Show(fail.Message);
            returnCode = false;
        }
        return returnCode;
    }

TableName contains "[MyTable]" and where contains "[MyTable ID]='4ffbd580-b17d-4731-b162-ede8d698e026'" which is a unique guid representing the row ID. TableName包含“ [MyTable]”,而其中包含“ [MyTable ID] ='4ffbd580-b17d-4731-b162-ede8d698e026'”,这是代表行ID的唯一GUID。

The function returns true, like it was successful, and no exception, but the rows are not deleted from DB, what's wong? 该函数返回true,就像它成功一样,也没有异常,但是没有从DB中删除行,这是什么呢?

This is the ExecuteNonQuery function 这是ExecuteNonQuery函数

 public int ExecuteNonQuery(string sql)
    {
        SQLiteConnection cnn = new SQLiteConnection(dbConnection);
        cnn.Open();
        SQLiteCommand mycommand = new SQLiteCommand(cnn);
        mycommand.CommandText = sql;
        int rowsUpdated = mycommand.ExecuteNonQuery();
        cnn.Close();
        return rowsUpdated;
    }

Firstly, you shouldn't just embed SQL like that. 首先,您不应该只是那样嵌入SQL。 You should use parameterized SQL, to avoid SQL injection attacks. 您应该使用参数化的 SQL,以避免SQL注入攻击。

Next, you should look at the return value of ExecuteNonQuery . 接下来,您应该查看ExecuteNonQuery的返回值。 Assuming it follows the normal pattern of ExecuteNonQuery , it should return the number of rows affected. 假设它遵循ExecuteNonQuery正常模式,则它应该返回受影响的行数。 I suspect it's returning 0, which will mean that nothing's matching your where clause. 我怀疑它返回0,这意味着没有任何内容与您的where子句匹配。

(I'd also stop catching Exception - probably stop catching anything , but at least catch something specific if you must. I'd get rid of the local variable, too, and just return directly when you know what you want to return...) (我也将停止捕获Exception可能会停止捕获任何东西 ,但至少必须捕获某些特定的东西。我也将摆脱局部变量,并且在知道要返回的内容时直接返回。) )

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

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