简体   繁体   English

如何在 ORMLITE android On Upgrade 方法中添加主键?

[英]how to add Primary Key in ORMLITE android On Upgrade method?

In my project I have used ORMLite.在我的项目中,我使用了 ORMLite。 Now I added a primary key for tje accountId field and also have changed DB Version.现在我为 tje accountId字段添加了一个主键,并且还更改了数据库版本。 Please help me, I don't know how to write query in onUpgrade(...) .请帮助我,我不知道如何在onUpgrade(...)编写查询。 For reference I have attached Account class below.作为参考,我在下面附上了Account类。

public class Account implements Serializable {
    @DatabaseField
    private String cdate;

    @DatabaseField(id=true)
    private Integer accountId;

    @DatabaseField
    private String Type;

    @DatabaseField
    private String Desc;

    @DatabaseField
    private String UpdatedDate;
}

I don't know how to write query in onUpgrade(...).我不知道如何在 onUpgrade(...) 中编写查询。

The trick is to figure out what Sqlite commands you need to make to add a primary key.诀窍是弄清楚添加主键需要执行哪些 Sqlite 命令。 You can figure this out by looking at the Sqlite docs for the primary key .您可以通过查看主键Sqlite 文档来弄清楚这一点。 There you can see that your accountId field should be defined as:在那里您可以看到您的accountId字段应定义为:

accountId INTEGER PRIMARY KEY ASC

So then your onUpdate(...) method should be something like:那么你的onUpdate(...)方法应该是这样的:

if (version of db is the old-version) {
    dao.executeRaw("ALTER TABLE account ADD COLUMN accountId INTEGER PRIMARY KEY ASC;");
}

You should do this conditionally based on the old version of the DB.您应该根据旧版本的数据库有条件地执行此操作。

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

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