当前位置: 首页 > 工具软件 > ActiveAndroid > 使用案例 >

ActiveAndroid 初学

宦高岑
2023-12-01

一、创建数据库

        Configuration.Builder builder = new Configuration.Builder(context);
        builder.setDatabaseName(DB_NAME);  //数据库名
        builder.setDatabaseVersion(DB_VERSION); //数据库版本号
        builder.setSqlParser(Configuration.SQL_PARSER_DELIMITED);
       //创建数据表,需要有对应的实体类,见下方
	builder.addModelClass(<span style="font-family: Arial, Helvetica, sans-serif;">Item</span>.class);  
        builder.addModelClass(Category.class);

        ActiveAndroid.initialize(builder.create());


实体类 Item

@Table(name="Items")
public class Item extends Model {

@Column(name="Name")
public String name;
@Column(name = "Category")
    public Category category;

    public Item() {
            super();
    }

    public Item(String name, Category category) {
            super();
            this.name = name;
            this.category = category;
    }
}

实体类Category

@Table(name = "Categories")
public class Category extends Model {
    @Column(name = "Name")
    public String name;

        // This method is optional, does not affect the foreign key creation.
    public List<Item> items() {
        return getMany(Item.class, "Category");
    }
}



二、数据库操作

1、保存数据

Category restaurants = new Category();
restaurants.name = "Restaurants";
restaurants.save();
Item item = new Item();
item.category = restaurants;
item.name = "Outback Steakhouse";
item.save();


2、保存多条数据,需要用到事物

ActiveAndroid.beginTransaction();
try {
        for (int i = 0; i < 100; i++) {
            Item item = new Item();
            item.name = "Example " + i;
            item.save();
        }
        ActiveAndroid.setTransactionSuccessful();
}
finally {
        ActiveAndroid.endTransaction();
}


3、删除数据

Item.delete(Item.class, 1);
也可以用类似sql的方式

new Delete().from(Item.class).where("Id = ?", 1).execute();


4、查询

查询一条数据

new Delete().from(Item.class).where("Id = ?", 1).execute();


查询多条数据

new Select()
        .from(Item.class)
        .where("Category = ?", category.getId())
        .orderBy("Name ASC")
        .execute();

分页查询数据

int mOffset ;//偏移量
new Select().from(AAA.class).where("category= 'NORMAL'").limit(10).offset(mOffset).execute();

联合查询

new Select().from(AAA.class).innerJoin(BBB.class)
                .on("aaa._id = bbb.user_id").where("bbb.id=?", id)
                .executeSingle()






 类似资料: