1. 程式人生 > >安卓開發-實現資料庫的CRUD操作

安卓開發-實現資料庫的CRUD操作

1.建立DBOpenHelper類繼承SQLiteOpenHelper:

public class DBOpenHelper extends SQLiteOpenHelper implements BaseColumns {
    public static final String DB_NAME = "contact.db";//資料庫的名稱
    public static final int DB_VERSION = 6;//資料庫的版本

    public static final String _TABLENAME = "_contactinfo";//表名
    public
static final String _USERNAME = "_username";//屬性名 public static final String _PHONE = "_phone";//屬性名 //通過傳入context物件建立資料庫物件 public DBOpenHelper(Context context) { super(context, DB_NAME, null, DB_VERSION); } //當資料庫當呼叫函式getWritableDatabase()/getReadableDatabase()且資料庫database檔案不在時執行
public void onCreate(SQLiteDatabase db) { db.execSQL("create table " + _TABLENAME + "(" + _ID + " integer primary key autoincrement, " + _USERNAME + " text, " + _PHONE + " text)"); } //版本更新時執行 public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) { } }

2.定義CRUD操作的介面IContactDao:

public interface IContactDao {
    //向表中插入一條資料
    boolean addContact(String username, String phone);

    //通過指定phone刪除表中的一條資料
    boolean deleteContact(String phone);

    //通過phone更新一條資料
    boolean updateContact(String username, String phone);

    //通過phone查詢該條資料
    String queryContact(String phone);
}

3.定義實現介面IContactDao的類ContactDaoImpl和ContactGoogleDaoImpl:

public class ContactDaoImpl implements IContactDao {
    private static DBOpenHelper mHelper;

    public ContactDaoImpl(Context c) {
        mHelper = new DBOpenHelper(c);
    }

    public boolean addContact(String username, String phone) {
        SQLiteDatabase database = mHelper.getWritableDatabase();

        database.execSQL("insert into " + DBOpenHelper._TABLENAME
                + " ("+DBOpenHelper._USERNAME+","+DBOpenHelper._PHONE+") values (?, ?)", new String[] { username,
                phone });
        return true;
    }

    public boolean deleteContact(String phone) {
        SQLiteDatabase database = mHelper.getWritableDatabase();

        database.execSQL("delete from " + DBOpenHelper._TABLENAME
                + " where "+DBOpenHelper._PHONE+" = ?", new String[] { phone });
        return true;
    }

    public boolean updateContact(String username, String phone) {
        SQLiteDatabase database = mHelper.getWritableDatabase();

        database.execSQL("update " + DBOpenHelper._TABLENAME
                + " set "+DBOpenHelper._USERNAME+" = ?, "+DBOpenHelper._PHONE+" = ?", new String[] { username,
                phone });
        return true;
    }

    public String queryContact(String phone) {
        SQLiteDatabase database = mHelper.getWritableDatabase();

        Cursor cursor = database.rawQuery("select "+DBOpenHelper._USERNAME+" from "+DBOpenHelper._TABLENAME+" where "+DBOpenHelper._PHONE+" = ?",
                new String[] { phone });
        if(cursor.moveToNext()){
            String username = cursor.getString(0);
            Log.v("aaa", username);
        }

        return null;
    }

}









public class ContactGoogleDaoImpl implements IContactDao {
    private DBOpenHelper dbHelper;

    public ContactGoogleDaoImpl(Context c) {
        dbHelper = new DBOpenHelper(c); 
    }

    public boolean addContact(String username, String phone) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();


        ContentValues values = new ContentValues();
        values.put(DBOpenHelper._USERNAME, username);
        values.put(DBOpenHelper._PHONE, phone);
        Long rawNum = database.insert(DBOpenHelper._TABLENAME, null, values);

        return rawNum != -1L;
    }

    public boolean deleteContact(String phone) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();

        int rawNum = database.delete(DBOpenHelper._TABLENAME,
                DBOpenHelper._PHONE + "= ?", new String[] { phone });
        return rawNum != 0;
    }

    public boolean updateContact(String username, String phone) {
        SQLiteDatabase database = dbHelper.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(DBOpenHelper._USERNAME, username);

        int rawNum = database.update(DBOpenHelper._TABLENAME, values,
                DBOpenHelper._PHONE + "= ?", new String[] { phone });

        return rawNum != 0; 
    }

    public String queryContact(String phone) {
        String result = "";

        SQLiteDatabase database = dbHelper.getReadableDatabase();
        Cursor cursor = database.query(DBOpenHelper._TABLENAME, new String[] {
                DBOpenHelper._USERNAME, DBOpenHelper._PHONE },
                DBOpenHelper._PHONE + "= ?", new String[] { phone }, null, null,
                null);

        String usernameValue = "";
        String phoneValue = "";
        while(cursor.moveToNext()){
            int usernameIndex = cursor.getColumnIndex(DBOpenHelper._USERNAME);
            usernameValue = cursor.getString(usernameIndex);

            int phoneIndex = cursor.getColumnIndex(DBOpenHelper._PHONE);
            phoneValue = cursor.getString(phoneIndex);
        }
        result += usernameValue;
        result += phoneValue;

        return result;
    }

}

4.在MainActivity中呼叫ContactDaoImpl中的方法:

public class MainActivity extends Activity {
    private IContactDao mContactDao = new ContactGoogleDaoImpl(this);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void addContactClick(View v){
        boolean ifChanged = mContactDao.addContact("張三", "111");
        Toast.makeText(this, ifChanged ? "新增成功" : "新增失敗", Toast.LENGTH_SHORT).show();
    }

    public void deleteContactClick(View v){
        boolean ifChanged = mContactDao.deleteContact("111");
        Toast.makeText(this, ifChanged ? "刪除成功" : "刪除失敗", Toast.LENGTH_SHORT).show();
    }

    public void updateContactClick(View v){
        boolean ifChanged = mContactDao.updateContact("李四", "111");
        Toast.makeText(this, ifChanged ? "修改成功" : "更新失敗", Toast.LENGTH_SHORT).show();
    }

    public void queryContactClick(View v){
        String result = mContactDao.queryContact("111");
        Toast.makeText(this, result, Toast.LENGTH_SHORT).show();

    }

}

5.Sqlite工具的使用:

1.位置:sdk/tools/sqlite3.exe

2.使用:
    2.1:cmd中,adb -s 模擬器名稱  shell
    2.2:cd /data/data/包名/databases
    2.3:sqlite3 資料庫檔名(contact.db)
            .tables : 檢視所有表
            sql語句  :執行
            sqlite.quit:退出