SQLite - 使用Count()获取行数 - 然后使用条件

时间:2016-01-03 23:07:17

标签: c# android sql sqlite xamarin

EDIT3: 我找到了答案。我感谢大家的帮助!这有点愚蠢,但我猜每个人都会犯这些错误。

问题:

我使用Xamarin for Android和Sqlite-net Nuget for SQL并使用以下代码

    protected void settingTags() {

        using (var connection = new SQLiteConnection (dbPath)) {

            var rowCount = connection.Table<User> ().Count ();

            if (rowCount <= 1) {
                // Setting the column "Person" of "Row where Primary Key is
                // "1" to the variable "person" in the table "User"

                // This gets the Row where the primary key attribute 
                // is "1"
                var presentUser = connection.Get<User> (1);

                // This sets the column "Persons" to "persons" where
                // person is an integer and is 1
                presentUser.Persons = persons;

                // This updates the Database
                connection.Update (presentUser);

                Log.Info (Tag, "User Data Updated");
            }
            else if (rowCount > 1) {
                for (int i = rowCount; i >= 1; i--) {
                    connection.Delete(new User(){ID=i});
                }
                settingTags ();
            }
        }
    }

这给了我一个空的异常错误。 我使用断点来查明错误,并以某种方式确定错误:

            if (rowCount <= 1) {

当然其他条件。

EDIT2: 但实际错误在于:

            var presentUser = connection.Get<User> (1);

我使用了文档中使用的代码。 并且主键有一行&#34; 1&#34; ...

我非常感谢任何帮助。 对不起,如果我在这个问题上使用了错误的标签或类似的东西,因为这是我的第一个。 :■

编辑:rowCount为6.所以它有一个值。

1 个答案:

答案 0 :(得分:0)

我发现了错误。我试图使用此方法作为递归方法,但for循环

            else if (rowCount > 1) {
                for (int i = rowCount; i >= 1; i--) {
                    connection.Delete(new User(){ID=i});
                }
                settingTags ();
            }

没有删除行。所以,你好无限循环。我改变了方法如下:

    protected void settingTags() {

        using (var connection = new SQLiteConnection (dbPath)) {

            var rowCount = connection.Table<User> ().Count ();

            var presentUser = connection.Get<User> (1);

            Log.Info (Tag, "rowCount: " + rowCount.ToString ());

            if (rowCount > 1) {
                Log.Info (Tag, "Database cleared");
                for (int i = rowCount; i > 0-1; i--) {
                    //var del = connection.Delete<User> (i);
                    var deleted = connection.Query<User> ("DELETE FROM User WHERE ID = ?", i);
                    Log.Info (Tag, "for loop i: " + i.ToString ());
                    Log.Info (Tag, "Rows deleted: " + deleted.ToString ());
                }
            }

            rowCount = connection.Table<User> ().Count ();

            if (rowCount <= 1) {
                presentUser.Persons = persons;
                connection.Update (presentUser);
                //var Users = connection.Query<User>("UPDATE User SET Persons = ? WHERE ID = 1", persons);
                Log.Info (Tag, "User Data Updated");
            }

        }
    }

它现在有效。 感谢所有人试图帮助我!