【问题标题】:When I try to update row in sqlite nothing happens in Xamarin当我尝试更新 sqlite 中的行时,Xamarin 中没有任何反应
【发布时间】:2021-06-04 01:57:54
【问题描述】:

当我尝试更新数据库中的行时没有任何反应,我做错了什么?

private void buttonUpdate_Clicked(object sender, EventArgs e)
    {
        string _dbPath = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "myDB.db3");
        var db = new SQLiteConnection(_dbPath);
        Airplane airplane = new Airplane()
        {
            SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + commentEntry.Text,
            Plane = planeEntry.Text.ToUpper(),
            Airline = airlineEntry.Text,
            Livery = liveryEntry.Text,
            Registration = registrationEntry.Text.ToUpper(),
            Airport = airportEntry.Text.ToUpper(),
            Comment = commentEntry.Text
        };
        db.Update(airplane);
    }

【问题讨论】:

  • 什么都没有发生?你期望会发生什么?如果您尝试更新现有行,PK 是什么?
  • 我改变了例如航空公司,但当我看起来和以前一样。这里用PK怎么样?
  • 更新需要设置表的PK才能工作。你在设置PK吗?通常在更新时,您从表中读取行,更改值,然后再次保存。但是您正在创建一个新对象,这让我认为您没有正确设置 PK。
  • 我只在 Import Id = (maxPK == null ? 1 : maxPK.Id + 1) 上使用 PK,那么我如何在此处更新 PK?
  • 如果要更新现有行,您保存的数据必须与数据库中已有的行具有相同的PK。这只是一个基本的数据库概念。

标签: c# sqlite xamarin


【解决方案1】:

为了更新现有行,数据库必须知道您正在更新哪一行。您可以通过设置主键来做到这一点

您正在创建一个新的Airplane 对象,但没有设置它的 PK (ID),因此数据库更新将失败,因为数据库不知道要更新哪一行

    Airplane airplane = new Airplane()
    {
        SearchId = planeEntry.Text + airlineEntry.Text + liveryEntry.Text + registrationEntry.Text + airportEntry.Text + commentEntry.Text,
        Plane = planeEntry.Text.ToUpper(),
        Airline = airlineEntry.Text,
        Livery = liveryEntry.Text,
        Registration = registrationEntry.Text.ToUpper(),
        Airport = airportEntry.Text.ToUpper(),
        Comment = commentEntry.Text
    };

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    • 2021-04-06
    相关资源
    最近更新 更多