You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用IDroid ORM框架访问SQLite数据库及实现增删改查与建表

Alright, let's dive into using the IDroid ORM framework for SQLite database interactions—covering table creation and all CRUD operations. I’ve worked with this framework on a couple of Android projects, so I’ll walk you through practical, easy-to-follow steps.

1. Prepping Your Project

First, add the IDroid dependency to your app-level build.gradle file (use the latest stable version available):

implementation 'com.github.yuweiguocn:IDroid:v1.0.1'

Then initialize IDroid in your Application class (this ensures it's ready to use across your app):

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        IDroid.init(this);
    }
}

Don’t forget to declare your Application class in AndroidManifest.xml.

2. Creating a Table

IDroid uses annotation-based entity classes to map to SQLite tables. Let’s create a User entity for example:

@Table(name = "user") // Maps to a table named "user" in SQLite
public class User {
    @PrimaryKey(autoGenerate = true) // Auto-incrementing primary key
    private long id;
    
    @Column(name = "username") // Maps to a column named "username"
    private String username;
    
    @Column(name = "age")
    private int age;
    
    @Column(name = "email")
    private String email;

    // *Critical*: IDroid requires a no-arg constructor for reflection
    public User() {}

    // Overloaded constructor for convenience (optional)
    public User(String username, int age, String email) {
        this.username = username;
        this.age = age;
        this.email = email;
    }

    // Getters and Setters (required for IDroid to access fields)
    public long getId() { return id; }
    public void setId(long id) { this.id = id; }
    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
    public String getEmail() { return email; }
    public void setEmail(String email) { this.email = email; }
}

IDroid will automatically create the table when you first interact with it. If you need to manually trigger table creation (for edge cases), use:

IDroid.getDb().createTable(User.class);
3. Inserting Records

Single Record Insert

Use the save() method to insert a single entity. It returns the auto-generated primary key ID:

User newUser = new User("john_doe", 28, "john@example.com");
long insertedId = IDroid.getDb().save(newUser);

Batch Insert

For inserting multiple records at once, use saveBatch()—it returns the number of successfully inserted records:

List<User> userList = new ArrayList<>();
userList.add(new User("jane_smith", 25, "jane@example.com"));
userList.add(new User("bob_brown", 30, "bob@example.com"));

int insertedCount = IDroid.getDb().saveBatch(userList);
4. Updating Records

Update by Primary Key

To update an existing record, set the primary key (so IDroid knows which row to target) and call update():

User updatedUser = new User();
updatedUser.setId(1); // Target the user with ID 1
updatedUser.setAge(29); // Update only the age field
updatedUser.setEmail("john_new@example.com"); // Update email too

int updatedCount = IDroid.getDb().update(updatedUser);

Conditional Update

Use the UpdateBuilder to update rows based on a condition (e.g., update all users over 25 with a new email):

int updatedCount = IDroid.getDb().update(User.class)
    .set("email", "updated@example.com")
    .where("age > ?", 25)
    .execute();
5. Deleting Records

Delete by Primary Key

Similar to updates, set the primary key on an entity and call delete():

User userToDelete = new User();
userToDelete.setId(1); // Delete the user with ID 1

int deletedCount = IDroid.getDb().delete(userToDelete);

Conditional Delete

Delete rows matching a condition (e.g., delete all users under 18):

int deletedCount = IDroid.getDb().delete(User.class)
    .where("age < ?", 18)
    .execute();

Delete All Records

To wipe an entire table:

IDroid.getDb().deleteAll(User.class);
6. Querying Records

IDroid’s QueryBuilder makes building complex queries straightforward.

Query Single Record by ID

User user = IDroid.getDb().findById(User.class, 1);

Query Single Record by Condition

User user = IDroid.getDb().findFirst(User.class)
    .where("username = ?", "john_doe")
    .execute();

Query All Records

List<User> allUsers = IDroid.getDb().findAll(User.class);

Conditional Query with Sorting

Get all users over 25, sorted by age in descending order:

List<User> userList = IDroid.getDb().findList(User.class)
    .where("age > ?", 25)
    .orderBy("age DESC")
    .execute();

Paged Query

Fetch the second page of results (10 records per page):

List<User> userList = IDroid.getDb().findList(User.class)
    .limit(10) // Records per page
    .offset(10) // Skip first 10 records (for page 2)
    .execute();

Query Specific Fields

Only fetch username and age columns (reduces data transfer):

List<User> userList = IDroid.getDb().findList(User.class)
    .select("username", "age")
    .execute();
7. Key Notes to Remember
  • Always include a no-arg constructor in your entity classes—IDroid uses reflection to create instances, and this is non-negotiable.
  • Use @Column(name = "column_name") if you want to map a field to a different column name than the field itself; if omitted, it uses the field name by default.
  • Avoid running database operations on the main thread (Android will throw a NetworkOnMainThreadException for long operations). Use Kotlin Coroutines, AsyncTask, or RxJava to offload work to background threads.
  • Primary keys should preferably be long (not int) to avoid overflow with large datasets.

内容的提问来源于stack exchange,提问作者user12240680

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 21:12:48