首先导入依赖
将GreenDAO添加到项目中
GreenDAO可在Maven Central上使用。请确保您使用的是最新版本检查这里 在这里
将以下Gradle配置添加到Android项目中:
// In your root build.gradle file:
buildscript {
repositories {
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.1.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
dependencies {
implementation 'org.greenrobot:greendao:3.2.2' // add library
}
greendao {
schemaVersion 1 //版本
daoPackage '生成文件包名' // 一般为app包名+生成文件的文件夹名
targetGenDir 'src/main/java.greendao' //生成文件路径
}
创建实体类,生成dao文件
@Entity
public class User {
@Id(autoincrement = true)
private Long id; //这里必须实用Long封装类型
private String userName;
}
之后一下或者Ctrl+F9(Make project),程序会自动编译生成dao文件,生成的文件一共有三个。
在src/main/java.greendao 上面设置的路径里 greendao包中..
之后自己创建工具类
public class SqliteUtils {
private SQLiteDatabase db;
private DaoMaster mDaoMaster;
private DaoSession mSession;
private SqliteUtils() {
}
private static SqliteUtils mSqliteUtils;
public static SqliteUtils getSqliteUtils() {
if (mSqliteUtils == null) {
mSqliteUtils = new SqliteUtils();
}
return mSqliteUtils;
}
//初始化
public void init(Context context) {
//这里是数据库的名字"ming1"
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "ming1");
db = helper.getWritableDatabase();
mDaoMaster = new DaoMaster(db);
mSession = mDaoMaster.newSession();
}
//增
public void insert(User user){
mSession.getUserDao().insert(user);
}
//查询全部
public List<User> queryAll(){
return mSession.getUserDao().loadAll();
}
//查询一条
public User query(Long key){
return mSession.getUserDao().load(key);
}
//删除全部
public void deleteAll(){
mSession.getUserDao().deleteAll();
}
//删除单个
public void delete(String key){
mSession.getUserDao().deleteByKey(Long.parseLong(key));
}
//更新
public void update(User user){
mSession.getUserDao().update(user);
}
}
之在项目中创建app包里面创建App类继承Application在
重写onCreate方法调用里面的init(Context context); 方法传入this
记得在
里面声明~~~
之后就可以使用了大概~