androidオリジナルSQLiteデータベースの使用

18763 ワード

sqliteはandroid内蔵の軽量級データベースとしていくつかの欠点があります...
1,Openhelperを作成する
package com.diandou.demo39_androidsqlite.sql;

import android.content.Context;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by baiya on 2018/2/7.
 */

public class DemoSQLiteOpenHelper extends SQLiteOpenHelper{


    private static final String TAG = "DemoSQLiteOpenHelper";

    public DemoSQLiteOpenHelper(Context context) {
        /**
         *     :
         *
         *      :    
         *      :        
         *      : null         
         *      :         (          )
         *
         */
        super(context, "demo.db", null, 2);
        Log.d(TAG,"DemoSQLiteOpenHelper");
    }

    /**
     *         
     *
     *    app              
     * @param db
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(
                "create table contactinfo (" +
                "id integer primary key autoincrement, " +
                "name varchar(20), " +
                "phone varchar(20))"
        );



        Log.d(TAG,"onCreate");
    }

    /**
     *         
     *
     *      super             
     *
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        Log.d(TAG,"onUpgrade + oldVersion: " + oldVersion + "newVersion: " + newVersion);
        switch (oldVersion) {
            case 2:
                db.execSQL(
                        "create table contactinfo2 (" +
                        "id integer primary key autoincrement, " +
                        "name varchar(20), " +
                        "phone varchar(20))"
                );   //      .      ,  upgrade  ,     
                break;
            case 3:
                db.execSQL("alter table contactinfo add category_id integer");
            default:

        }
    }



}

2 daoを作成
package com.diandou.demo39_androidsqlite.sql;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

/**
 * Created by baiya on 2018/2/7.
 */

public class DemoDao {
    private DemoSQLiteOpenHelper helper;

    public DemoDao(Context context) {
        helper = new DemoSQLiteOpenHelper(context);
    }

    /**
     *       
     * @param name      
     * @param phone      
     * @return                 -1      
     */
    public long add(String name, String phone, String category_id){
        SQLiteDatabase db = helper.getWritableDatabase();
        //db.execSQL("insert into contactinfo (name,phone) values (?,?)", new Object[]{name,phone});
        ContentValues values = new ContentValues();
        values.put("name", name);
        values.put("phone", phone);
        values.put("category_id", category_id);
        //     sql     .
        long rowid = db.insert("contactinfo", null, values);
        //         
        db.close();
        return rowid;
    }
    /**
     *           
     * @param name           
     * @return   0                  int          
     */
    public int delete(String name){
        //          .
        SQLiteDatabase db = helper.getWritableDatabase();
        //db.execSQL("delete from contactinfo where name=?", new Object[]{name});
        int rowcount = db.delete("contactinfo", "name=?", new String[]{name});
        db.close();
        //           , name    
        return rowcount;
    }
    /**
     *          
     * @param newphone       
     * @param name          
     * @return 0           , >0               
     */
    public int update(String newphone , String name){
        //          
        SQLiteDatabase db = helper.getWritableDatabase();
        //db.execSQL("update contactinfo set phone =? where name=?", new Object[]{newphone,name});
        ContentValues values = new ContentValues();
        values.put("phone", newphone);
        int rowcount =  db.update("contactinfo", values, "name=?", new String[]{name});
        db.close();
        return rowcount;
    }
    /**
     *           
     * @param name        
     * @return     
     */
    public String getPhoneNumber(String name){
        String phone = null;
        SQLiteDatabase db = helper.getReadableDatabase();
        //Cursor  cursor = db.rawQuery("select phone from contactinfo where name=?", new String[]{name});
        Cursor cursor =  db.query("contactinfo", new String[]{"phone"}, "name=?", new String[]{name}, null, null, null);
        if(cursor.moveToNext()){//            ,          
            phone = cursor.getString(0);
        }
        cursor.close();//     ,    
        db.close();//     ,    
        return phone;
    }


    /**
     *       
     * @return
     */
    public String getAll(){
        String all = "";
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor =  db.query("contactinfo", new String[]{"phone", "name", "category_id"}, null, null, null, null, null);
        while (cursor.moveToNext()){//            ,          
            all += cursor.getString(0)+"..."+cursor.getString(1)+"..."+cursor.getString(2)+"///";
        }
        cursor.close();//     ,    
        db.close();//     ,    
        return all;
    }

    /**
     *       
     * @return
     */
    public String updateField(){
        String allTable = "";
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select name from sqlite_master where type='table' order by name", null);
        while(cursor.moveToNext()){
            //     
            String name = cursor.getString(0);
            allTable += name+"....";
        }

        return allTable;
    }



}

3、App起動入口は一度初期化して、構成を忘れないでください.
package com.diandou.demo39_androidsqlite;

import android.app.Application;

import com.diandou.demo39_androidsqlite.sql.DemoSQLiteOpenHelper;

/**
 * Created by baiya on 2018/2/22.
 */

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();

        initSqlite();

    }

    /**
     *       
     */
    private void initSqlite() {
        DemoSQLiteOpenHelper openHelper = new DemoSQLiteOpenHelper(this);

    }
}

4、activityでテスト
package com.diandou.demo39_androidsqlite;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.diandou.demo39_androidsqlite.sql.DemoDao;

public class MainActivity extends AppCompatActivity {

    private DemoDao demoDao;
    private EditText mEtName;
    private EditText mEtPhone;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mEtName = (EditText) findViewById(R.id.mEtName);
        mEtPhone = (EditText) findViewById(R.id.mEtPhone);

        demoDao = new DemoDao(this);

    }


    public void add(View view){
        String name = mEtName.getText().toString();
        String phone = mEtPhone.getText().toString();
        String category_id = "fdfdfd";
        long add = demoDao.add(name, phone,category_id);
        if (add != -1){
            Toast.makeText(this, "    " + add, 0).show();
        }
    }

    public void delete(View view){
        String name = mEtName.getText().toString();
        int delete = demoDao.delete(name);
        if (delete != 0){
            Toast.makeText(this, "    " + delete, 0).show();
        }
    }

    public void update(View view){
        String name = mEtName.getText().toString();
        String phone = mEtPhone.getText().toString();
        //  phone  name
        int update = demoDao.update(phone, name);
        if (update != 0){
            Toast.makeText(this, "    " + update, 0).show();
        }

    }

    public void query(View view){
//        String name = mEtName.getText().toString();
//        String phoneNumber = demoDao.getPhoneNumber(name);
//        String phoneNumber_1 = demoDao.getPhoneNumber(name);
//        if (!TextUtils.isEmpty(phoneNumber_1)) {
//            Toast.makeText(this, "    " + phoneNumber_1, 0).show();
//        }

        String all = demoDao.getAll();
        if (!TextUtils.isEmpty(all)) {
            Toast.makeText(this, "    --" + all, 0).show();
        }



    }

    public void allTableName(View view) {
        String all = demoDao.updateField();
        if (!TextUtils.isEmpty(all)) {
            Toast.makeText(this, "    --" + all, 0).show();
        }
    }


}

sqliteテーブルのフィールドは変更できませんが、updateメソッドを追加できるのはアップグレード用です.onCreateメソッドはappが初めて携帯電話にインストールされたときに呼び出されるだけで、テーブルを作成した後は行かないので、updateでテーブルを作成したり、ワードセグメントを増やしたりしたら、onCreateにも1部書いてください