Android中,可以使用SugarORM框架进行数据库的操作。
1. 不用写复杂的sql语句,而用简单的API即可完成创建和操纵数据
2. 可以在原有的Bean上仅仅添加小的修改而复用Bean
3. 简化而明了的数据库设计和创建过程,同时提供表的一对多的支持
详细使用方法可以参考:
http://blog.youkuaiyun.com/Norwaya007/article/details/51595908
开源库下载地址:
https://github.com/satyan/sugar
这里,主要介绍一下使用过程中注意的地方,以及遇到的问题。
1. 由于table名或者字段名不一致导致的错误:
android.database.sqlite.SQLiteException: no such table: INFO_MODEL (code 1): , while compiling: SELECT * FROM InfoModel WHERE parentid = ? ORDER BY ID DESC
at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:886)
at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:497)
at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:44)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1314)
at android.database.sqlite.SQLiteDatabase.queryWithFactory(SQLiteDatabase.java:1161)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1032)
at android.database.sqlite.SQLiteDatabase.query(SQLiteDatabase.java:1238)
at com.orm.SugarRecord.find(SugarRecord.java:201)
原因:
Bean的属性名所采用驼峰命名法,那么大写的字母会在创建的表中字段转换成下划线。
我的Bean名称是InfoModel,但查询语句中,没有加下划线,所以导致错误发生。
总结:如果你用sql语句,表名要写正确了,不要忘了加下划线。
同理,表的字段也是一样。
2. Bean的字段和SugarRecord中的id字段重复。
在SugarRecord类中,有一个字段id,通常是作为主key来使用的,如果不主动赋值,是自增的。SugarRecord的定义(摘取一少部分):
public class SugarRecord { public static final String SUGAR = "Sugar"; private Long id = null; private static SQLiteDatabase getSugarDataBase() { return getSugarContext().getSugarDb().getDB(); } public static <T> int deleteAll(Class<T> type) { return deleteAll(type, null); } public static <T> int deleteAll(Class<T> type, String whereClause, String... whereArgs) { return getSugarDataBase().delete(NamingHelper.toSQLName(type), whereClause, whereArgs); } public static <T> Cursor getCursor(Class<T> type, String whereClause, String[] whereArgs, String groupBy, String orderBy, String limit) { Cursor raw = getSugarDataBase().query(NamingHelper.toSQLName(type), null, whereClause, whereArgs, groupBy, null, orderBy, limit); return new SugarCursor(raw); }
错误的定义:
public class InfoModel extends SugarRecord {
private String name;
private long id;
......
}
解决方法:采用@SerializedName注解,重新指定id的名称。例如,
public class InfoModel extends SugarRecord {
@Expose
private String name;
@Expose
@SerializedName("id")
private long infoId;
......
}
另外,最好将Bean中所有的字段都用@Expose来注解。
<本篇完>。