What are the best practices for SQLite on Android?

前端 未结 10 2010
自闭症患者
自闭症患者 2020-11-21 23:45

What would be considered the best practices when executing queries on an SQLite database within an Android app?

Is it safe to run inserts, deletes and select queries

10条回答
  •  爱一瞬间的悲伤
    2020-11-22 00:00

    You can try to apply new architecture approach anounced at Google I/O 2017.

    It also includes new ORM library called Room

    It contains three main components: @Entity, @Dao and @Database

    User.java

    @Entity
    public class User {
      @PrimaryKey
      private int uid;
    
      @ColumnInfo(name = "first_name")
      private String firstName;
    
      @ColumnInfo(name = "last_name")
      private String lastName;
    
      // Getters and setters are ignored for brevity,
      // but they're required for Room to work.
    }
    

    UserDao.java

    @Dao
    public interface UserDao {
      @Query("SELECT * FROM user")
      List getAll();
    
      @Query("SELECT * FROM user WHERE uid IN (:userIds)")
      List loadAllByIds(int[] userIds);
    
      @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
           + "last_name LIKE :last LIMIT 1")
      User findByName(String first, String last);
    
      @Insert
      void insertAll(User... users);
    
      @Delete
      void delete(User user);
    }
    

    AppDatabase.java

    @Database(entities = {User.class}, version = 1)
    public abstract class AppDatabase extends RoomDatabase {
      public abstract UserDao userDao();
    }
    

提交回复
热议问题