Android 数据库框架ormlite 使用
在Android中使用OrmLite框架,首先需要在项目的build.gradle
文件中添加OrmLite库依赖。以下是一个简单的使用OrmLite的例子:
- 添加依赖到
build.gradle
文件:
dependencies {
implementation 'com.j256.ormlite:ormlite-android:5.2' // 使用最新版本
implementation 'com.j256.ormlite:ormlite-core:5.2' // 仅当不需要Android特定类时不需要
}
- 创建一个Java实体类:
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
@DatabaseTable(tableName = "users")
public class User {
@DatabaseField(id = true)
private int id;
@DatabaseField(columnName = "name")
private String name;
// 必要的构造器、getter和setter
}
- 使用OrmLite操作数据库:
import com.j256.ormlite.dao.Dao;
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private Dao<User, Integer> userDao;
// 构造器,需要传递上下文和数据库助手
public DatabaseHelper(Context context) {
super(context, "database-name.db", null, 1);
}
@Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, User.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "创建数据库表失败", e);
}
}
@Override
public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVersion, int newVersion) {
try {
TableUtils.dropTable(connectionSource, User.class, true);
onCreate(sqliteDatabase, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "更新数据库表失败", e);
}
}
public Dao<User, Integer> getUserDao() throws SQLException {
if (userDao == null) {
userDao = getDao(User.class);
}
return userDao;
}
// 关闭DAO
public void closeDao() throws SQLException {
if (userDao != null) {
userDao.close();
}
}
}
- 使用
DatabaseHelper
来操作数据库:
DatabaseHelper helper = new DatabaseHelper(context);
try {
Dao<User, Integer> userDao = helper.getUserDao();
User user = new User();
user.setName("张三");
userDao.create(user);
List<User> users = userDao.queryForAll();
// 处理查询结果
} catch (SQLException e) {
Log.e(TAG, "数据库操作失败", e);
} finally {
try {
helper.closeDao();
} catch (
评论已关闭