我在 Android 上编写应用程序并使用 SQlite 数据库。 我希望能够根据用户的选择将列添加到我的表中。 因此用户可以将他想要的任何列添加到表中。例如,用户有“动物”表,他想为“狗”、“猫”和“鱼”添加列。
我已经阅读了一些解决方案,但没有找到可以帮助我的解决方案。 我读到添加列的简单方法是使用:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE " + TableName + " ADD COLUMN " + ColumnName);
}
}
但是我的问题是我无法选择将由用户选择添加到表中的列的名称,没有字符串参数。 所以我尝试使用类似这样的东西,并直接调用它。
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion, String newColumnName) {
// If you need to add a column
if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE " + TableName + " ADD COLUMN " + newColumnName);
}
}
但是我得到了这个方法的错误。
我还有一个关于数据库版本的问题。 调用 onCreate 时会自动调用 onUpgrade 方法。 在 onUpgrade 中有数据库版本的 oldVersion 和 newVersion 参数。什么时候设置 oldVersion 和 newVersion 参数?我如何将 newVersion 参数设置为 2,3,4...?
最佳答案
您可以创建一个辅助表来保存额外的列数据。对主表的查询可以转换为对新 View 的查询。
create table if not exists animal (pk integer primary key, name);
create table if not exists animal_aux (animal_pk, col_name, col_val);
create view if not exists animal_view
as select animal.name as name,
ct.col_val as cat,
dt.col_val as dog
from animal, animal_aux as ct, animal_aux as dt
where animal.pk = ct.animal_pk
and animal.pk = dt.animal_pk
and ct.col_name = 'cat'
and dt.col_name = 'dog'
;
应该增强此架构,使 animal_pk, col_name
成为主键,或至少在 animal_aux
中唯一
。当您在 animal
表中插入或删除条目时,您可能还需要触发器来添加或删除 aux 表中的条目。
例子:
sqlite> select * from animal_view;
sqlite> insert into animal values (NULL, 'fred');
sqlite> select * from animal_view;
sqlite> select * from animal;
1|fred
sqlite> insert into animal_aux values (1, "dog", "beagle");
sqlite> insert into animal_aux values (1, "cat", "siamese");
sqlite> select * from animal_view;
fred|siamese|beagle
sqlite>
每次添加虚拟列时,您都需要
drop view animal_view;
然后使用适当的额外列和 where
子句重新创建它。
关于android - 如何使用 Android SQLite 数据库制作动态列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16323183/