Android 데이터베이스 에 데이터 저장(Room,GreenDao,Sqlite)

목차
Android 데이터베이스 에 데이터 저장(Room,GreenDao,Sqlite)
1.GreenDao 의 데이터베이스 프레임 워 크:
2.Google 의 Room 구성 요소 프레임 워 크(홈 페이지 학습 주소:학습 Room 참조):
1.AndroidStudio 의 gradle 의존:
2.실체 구조:
3.통합 RoomDatabase 의 데이터베이스:
4.Dao 의 작업 종류:
5.간단 한 사용:
3.Android Sqlite:
1.테이블 을 만 드 는 필드 클래스:
2.Sqlite 의 Helpr 류:
3.간단 한 첨삭 검사 도구 류:
Android 데이터베이스 에 데이터 저장(Room,GreenDao,Sqlite)
1.GreenDao 의 데이터베이스 프레임 워 크:
그린 다 오 가서 쓰 는 거.
2.Google 의 Room 구성 요소 프레임 워 크(홈 페이지 학습 주소:학습 Room 참조):
1.AndroidStudio 의 gradle 의존:
//  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"

2.실체 구조:
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;
}

3.통합 RoomDatabase 의 데이터베이스:
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();
}

4.Dao 의 작업 종류:
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 getAll();

    @Query("SELECT * FROM person WHERE id in (:userIds)")
    public List 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);
}

5.간단 한 사용:
//                ,        
//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 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();

3.Android Sqlite:
1.테이블 을 만 드 는 필드 클래스:
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";
    }
}

2.Sqlite 의 Helpr 류:
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
 * 

* 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); } }


3.간단 한 첨삭 검사 도구 류:
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
 * 

* 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(); } } }


좋은 웹페이지 즐겨찾기