天天看點

android 讀取本地資料庫db檔案(Android sqlite)

我們知道Android中有四種資料存儲方式:

  1. SharedPreference存儲
  2. content provider
  3. SQLite資料庫存儲
  4. 檔案存儲

今天我們主要說 本地資料庫sqlite這種方式,實作讀取一個本地資料庫db檔案的功能。為了友善說明,我舉個例子來講:

我們建立一個本地資料庫,裡面包含兩張表 一個使用者表user  一個性别表 gender

android 讀取本地資料庫db檔案(Android sqlite)
android 讀取本地資料庫db檔案(Android sqlite)

要求:1.将使用者表中使用者查詢出來,性别需要顯示男女,用listView展示出來。

           2.修改 将使用者表中  王傑修改為李四

            3.增加長按删除功能

非常簡單的功能,那麼我們實作這個需要做以下幾步操作。

1.将本地資料庫db檔案拷貝到項目中

2.将項目中db檔案寫入到本地檔案夾中

3.增加打開資料庫以及資料讀取邏輯

4.增加删除邏輯 ,增加修改邏輯。

需要注意的有幾點:

1)拷貝資料庫涉及到讀寫 ,是以權限這塊需要注意,如果是22以上的需要申請權限,否則會報錯。

2)assets檔案夾是在main檔案夾下面建和res是平級,之前很多來面試的還把檔案夾都放錯了。

3)讀取使用者時候,性别一欄是需要做關聯查詢的 ,因為使用者表性别用的是字典值。

Android拷貝邏輯代碼

package com.example.testdemo.util;

import android.content.Context;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FileUtil {

    private static String mWorkPath = null;
    private static String mRootPath = null;
    private static Boolean mGetSDpath = false;
    private final static String DB_PATH_NAME = "database/";
    public static long copyTime = 0;

    private static Context mContext;

    public static String getRootPath() {
        if (!mGetSDpath || mRootPath == null) {
            mGetSDpath = true;
            boolean sdCardExist = Environment.getExternalStorageState().equals(
                    Environment.MEDIA_MOUNTED); // 判斷sd卡是否存在
            if (sdCardExist) {
                File sdDir = Environment.getExternalStorageDirectory();// 擷取跟目錄
                mRootPath = sdDir.toString();
            } else {
                mRootPath = mContext.getFilesDir().toString();
            }
        }
        if (!mRootPath.endsWith("/"))
            mRootPath += "/";
        return mRootPath;
    }

    /**
     * 設定工作目錄
     *
     * @param context app context,不然會造成記憶體洩漏
     * @param path
     */
    public static void setWorkPath(Context context, String path) {
        mContext = context;
        if (null != getRootPath()) {
            mWorkPath = mRootPath + path;
        }
        if (!mWorkPath.endsWith("/")) {
            mWorkPath += "/";
        }

        File file = new File(mWorkPath);
        if (!file.exists()){
            boolean b = file.mkdirs();
        }
    }

    public static String getDBpath() {
        File file = new File(mWorkPath + DB_PATH_NAME);
        if (!file.exists())
            file.mkdirs();
        return mWorkPath + DB_PATH_NAME;
    }

    public static void copyAccessDB(Context context) {
        try {
            String[] dbNames = context.getAssets().list("db");
            for (String dbName : dbNames) {
                long startTime = System.currentTimeMillis();
                String filePath = FileUtil.getDBpath() + dbName;
                File dbFile = new File(filePath);
                if (!dbFile.exists()) {
                    FileOutputStream fos = null;
                    try {
                        dbFile.createNewFile();
                    }catch (Exception e){
                    }
                    InputStream is = context.getAssets().open("db/" + dbName);
                    fos = new FileOutputStream(dbFile);

                    byte[] buffer = new byte[2048];
                    int len = -1;
                    while ((len = is.read(buffer)) != -1) {
                        fos.write(buffer, 0, len);
                    }
                    fos.close();
                    long endTime = System.currentTimeMillis();
                    long useTime = endTime - startTime;
                    copyTime += useTime;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

      

Android  本地 操作資料庫邏輯(查,删,改)

package com.example.testdemo.util;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Environment;

import com.example.testdemo.bean.User;

import java.util.ArrayList;
import java.util.List;

public class DBManager {

    private Context mContext;
    private SQLiteDatabase mDB;
    private static String dbPath = FileUtil.getDBpath() + "/Test.db";
    private static DBManager instance = null;

    public DBManager() {
    }

    public static DBManager getInstance() {
        if (instance == null) {
            instance = new DBManager();
        }
        return instance;
    }

    /**
     * 打開資料庫
     */
    private void openDB() {
        if (isSDCard()) {
            if (mDB == null || !mDB.isOpen())
                mDB = SQLiteDatabase.openDatabase(dbPath, null,
                        SQLiteDatabase.OPEN_READWRITE);
        }
    }
    private boolean isSDCard() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    //查詢選擇題
    public List<User> queryUser() {
        List<User> userList = new ArrayList<User>();
        User user= null;
        openDB();
        try {
            String sql = " select a.id,a.name,a.age,a.phoneNum,b.name as sexName from user a,gender b where a.sex= b.type";
            Cursor cursor = mDB.rawQuery(sql, null);
            while (cursor.moveToNext()) {
                String id = cursor.getString(cursor.getColumnIndex("id"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                String sex = cursor.getString(cursor.getColumnIndex("sexName"));
                String age = cursor.getString(cursor.getColumnIndex("age"));
                String phoneNum = cursor.getString(cursor.getColumnIndex("phoneNum"));
                user= new User();
                user.setId(id);
                user.setName(name);
                user.setAge(age);
                user.setPhoneNum(phoneNum);
                user.setSex(sex);
                userList.add(user);
            }
            cursor.close();
            return userList;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public void updateUser() {
        openDB();
        String sql = " update  user  set name = '李四' where name = '王傑' ";
        mDB.execSQL(sql);
    }

    public void deleteUser(String id) {
        openDB();
        mDB.delete("user", " id = ? ", new String[]{id});
    }


}

      

基本最核心的就這些代碼,不是很複雜,貼上效果圖。

繼續閱讀