SQLite表没有更新

时间:2019-06-12 18:18:58

标签: c# sqlite xamarin.android android-sqlite

我有问题。我创建了一个SwitchButton,并希望将状态存储在数据库表中。所以我创建了以下代码进行调试:

SettingSwitch.CheckedChange += (s, b) =>
{
    SettingDb testsetting = new SettingDb
    {
        Name = mItems[position].Name,
    };

    SettingDb test = MainActivity.db.SelectRowFromTableSettings(testsetting);

    if (test != null)
    {
        bool SwitchValueBool = Convert.ToBoolean(test.Value);
    }


    bool isChecked = ValueDictionary[position];
    if(isChecked == true)
    {
        isChecked = false;
    }
    else if(isChecked == false)
    {
        isChecked = true;
    }

    SettingDb setting = new SettingDb()
    {
        Name = SettingName.Text,
        Type = "Switch",
        Value = isChecked.ToString()
    };

    MainActivity.db.UpdateTableSettings(setting);
    ValueDictionary[position] = isChecked;

    SettingDb test2 = MainActivity.db.SelectRowFromTableSettings(testsetting);

    if (test2 != null)
    {
        bool SwitchValueBool = Convert.ToBoolean(test2.Value);
    }
};

预期结果应为:

test.Value = False
test2.Value = Opposite of test.Value, so True

但是现在我从表中获得的值始终为False。这是更新功能:

string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
public bool UpdateTableSettings(SettingDb setting)
{
    try
    {

        using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
        {
            connection.BeginTransaction();
            connection.Query<SettingDb>("UPDATE SettingDb SET Value=? WHERE Name=?", setting.Value, setting.Name);
            //connection.Update(setting);
            connection.Commit();
            return true;
        }
    }
    catch (SQLiteException ex)
    {
        Log.Info("SQLiteEx", ex.Message);
        return false;
    }
}
public SettingDb SelectRowFromTableSettings(SettingDb setting)
{
    try
    {
        using (var connection = new SQLiteConnection(System.IO.Path.Combine(folder, "Settings.db")))
        {
            return connection.Query<SettingDb>("SELECT * FROM SettingDb WHERE Name=?", setting.Name).FirstOrDefault();
        }
    }
    catch (SQLiteException ex)
    {
        Log.Info("SQLiteEx", ex.Message);
        return null;
    }
}

表值未更新!!! 有人可以告诉我我在做什么错吗? 请让我知道!

1 个答案:

答案 0 :(得分:1)

根据您的描述,您想更新sqlite数据库表,请看下面的代码并修改更新功能。

 static void UpdateDatabase(int primaryKey, string newText, int newValue)
{
    string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "mydatabase.db");
    var db = new SQLiteConnection(path, false);
    string sql = "UPDATE MyTable SET MyTextColumn = ?, MyValueColumn = ? WHERE MyPrimaryKey= ?";
    string[] parms = new String[] { newText, newValue.ToString(), primaryKey.ToString() };
    var cmd = db.CreateCommand(sql, parms);
    cmd.ExecuteNonQuery();
}