目录
Android数据库存储数据(Room、GreenDao、Sqlite)
二、Google的Room组件框架(参考官网学习地址:学习Room):
//在 defaultConfig下配置该属性,那么创建的数据库的信息会在src的同目录下创建schemas文件夹
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
}
}
//=====================================================================
implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
package com.zbv.newdesttop.Entities;
import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
/**
* author: qzx
* Date: 2019/3/1 13:52
*/
@Entity
public class Person {
@PrimaryKey(autoGenerate = true)
public int id;
@ColumnInfo(name = "first_name")
public String firstName;
@ColumnInfo(name = "last_name")
public String lastName;
}
package com.zbv.newdesttop.roomdao;
import android.arch.persistence.room.Database;
import android.arch.persistence.room.RoomDatabase;
import com.zbv.newdesttop.Entities.Person;
/**
* author: qzx
* Date: 2019/3/1 14:12
*/
@Database(entities = {Person.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
//要采取单例模式,因为每次创建会代价昂贵
public abstract PersonDao personDao();
}
package com.zbv.newdesttop.roomdao;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import android.arch.persistence.room.Update;
import com.zbv.newdesttop.Entities.Person;
import java.util.List;
/**
* author: qzx
* Date: 2019/3/1 14:04
*/
@Dao
public interface PersonDao {
@Query("SELECT * FROM person")
public List<Person> getAll();
@Query("SELECT * FROM person WHERE id in (:userIds)")
public List<Person> getAllById(int[] userIds);
@Query("SELECT * FROM person WHERE first_name LIKE :first AND last_name LIKE :last LIMIT 1")
public Person findByName(String first, String last);
@Update
public void updateUsers(Person... person);
@Insert
public void insertAll(Person... person);
@Delete
public void delete(Person person);
}
//如果操作数据库不开线程执行会报错,不能再主线程执行
//Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
AppDatabase appDatabase = Room.databaseBuilder(this, AppDatabase.class, "roomdao.db").build();
personDao = appDatabase.personDao();
//添加数据
new Thread(new Runnable() {
@Override
public void run() {
Person person = new Person();
person.firstName = "周";
person.lastName = "尘";
Person person_2 = new Person();
person_2.firstName = "王";
person_2.lastName = "福";
personDao.insertAll(person, person_2);
Log.e("zbv", "add complete...");
}
}).start();
//查询数据
new Thread(new Runnable() {
@Override
public void run() {
Log.e("zbv", "to query....");
List<Person> ps = personDao.getAll();
Log.e("zbv", "isNull?" + (ps == null) + ";size=" + ps.size());
for (Person person : ps) {
Log.e("zbv", "id=" + person.id + ";firstName=" + person.firstName + ";lastName=" + person.lastName);
}
}
}).start();
package com.zbv.newdesttop.database;
import android.provider.BaseColumns;
/**
* author: qzx
* Date: 2019/3/1 16:40
*/
public final class SqliteTables {
private SqliteTables() {
}
public static class Customer implements BaseColumns {
public static final String TABLE_NAME = "customer";
public static final String COLUME_ONE = "name";
public static final String COLUME_TWO = "address";
}
}
package com.zbv.newdesttop.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* author: qzx
* Date: 2019/2/28 14:35
* <p>
* sqlite本地数据库保存应用数据
*/
public class ZBVSqliteHelper extends SQLiteOpenHelper {
// If you change the database schema, you must increment the database version.
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "sqlite.db";
//主键自增
private static final String SQL_CREATE_ENTRIES =
"CREATE TABLE " + SqliteTables.Customer.TABLE_NAME + " (" +
SqliteTables.Customer._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
SqliteTables.Customer.COLUME_ONE + " TEXT," +
SqliteTables.Customer.COLUME_TWO + " TEXT)";
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + SqliteTables.Customer.TABLE_NAME;
public ZBVSqliteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// This database is only a cache for online data, so its upgrade policy is
// to simply to discard the data and start over
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
}
package com.zbv.newdesttop.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.provider.BaseColumns;
import android.util.Log;
import com.zbv.newdesttop.Entities.Customer;
import java.util.ArrayList;
import java.util.List;
/**
* author: qzx
* Date: 2019/2/28 16:35
* <p>
* sqlite数据库操作,增删改查
*/
public class ZBVSqliteOperate {
public static ZBVSqliteOperate zbvSqliteOperate = null;
private ZBVSqliteHelper dbHelper;
private ZBVSqliteOperate(Context context) {
dbHelper = new ZBVSqliteHelper(context);
}
public static ZBVSqliteOperate getInstance(Context context) {
if (zbvSqliteOperate == null) {
synchronized (ZBVSqliteOperate.class) {
if (zbvSqliteOperate == null) {
zbvSqliteOperate = new ZBVSqliteOperate(context);
}
}
}
return zbvSqliteOperate;
}
public void insert(Customer customer) {
// Gets the data repository in write mode
SQLiteDatabase database = dbHelper.getWritableDatabase();
// Create a new map of values, where column names are the keys
ContentValues values = new ContentValues();
values.put(SqliteTables.Customer.COLUME_ONE, customer.getName());
values.put(SqliteTables.Customer.COLUME_TWO, customer.getAddress());
//第二个参数:If you specify null, like in this code sample, the framework does not insert a row when there are no values.
long newRowId = database.insert(SqliteTables.Customer.TABLE_NAME, null, values);
}
public void delete(String column, String columnValue) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
// Define 'where' part of query.
String selection = column + " LIKE ?";
// Specify arguments in placeholder order.
String[] selectionArgs = {columnValue};
// Issue SQL statement.
int deletedRows = db.delete(SqliteTables.Customer.TABLE_NAME, selection, selectionArgs);
}
public void update(String column, String updateValue) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// New value for one column
String title = "MyNewTitle";
ContentValues values = new ContentValues();
values.put(column, title);
// Which row to update, based on the title
String selection = column + " LIKE ?";
String[] selectionArgs = {updateValue};
int count = db.update(
SqliteTables.Customer.TABLE_NAME,
values,
selection,
selectionArgs);
}
public void query() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
// Define a projection that specifies which columns from the database
// you will actually use after this query.
String[] projection = {
BaseColumns._ID,
SqliteTables.Customer.COLUME_ONE,
SqliteTables.Customer.COLUME_TWO
};
// Filter results WHERE "title" = 'My Title'
String selection = SqliteTables.Customer.COLUME_ONE + " = ?";
String[] selectionArgs = {"七子笑"};
// How you want the results sorted in the resulting Cursor
String sortOrder =
SqliteTables.Customer.COLUME_ONE + " DESC";
Cursor cursor = db.query(
SqliteTables.Customer.TABLE_NAME, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
sortOrder // The sort order
);
List itemIds = new ArrayList<>();
while (cursor.moveToNext()) {
long itemId = cursor.getLong(
cursor.getColumnIndexOrThrow(SqliteTables.Customer._ID));
Log.e("zbv", "itemId=" + itemId);
itemIds.add(itemId);
}
cursor.close();
}
/**
* 关闭数据库
*/
public void closeDB() {
//Since getWritableDatabase() and getReadableDatabase() are expensive to call when the database is closed,
// you should leave your database connection open for as long as you possibly need to access it
if (dbHelper != null) {
dbHelper.close();
}
}
}