最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Android學(xué)習(xí)筆記-保存數(shù)據(jù)到SQL數(shù)據(jù)庫中(Saving Data in SQL Databases)

 更新時間:2014年10月15日 12:55:49   投稿:mdxy-dxy  
這篇文章主要介紹了Android學(xué)習(xí)筆記-保存數(shù)據(jù)到SQL數(shù)據(jù)庫中的(Saving Data in SQL Databases)

知識點(diǎn):

1.使用SQL Helper創(chuàng)建數(shù)據(jù)庫
2.數(shù)據(jù)的增刪查改(PRDU:Put、Read、Delete、Update)

背景知識:

上篇文章學(xué)習(xí)了android保存文件,今天學(xué)習(xí)的是保存數(shù)據(jù)到SQL數(shù)據(jù)庫中。相信大家對數(shù)據(jù)庫都不陌生。對于大量重復(fù)的,有特定結(jié)構(gòu)的數(shù)據(jù)的保存,用 SQL數(shù)據(jù)庫 來保存是最理想不過了。

下面將用一個關(guān)于聯(lián)系人的數(shù)據(jù)庫Demo來具體學(xué)習(xí)。

具體知識:

1.定義Contract類

在創(chuàng)建SQL數(shù)據(jù)庫之前,要創(chuàng)建Contract類。那什么是Contract類呢?

復(fù)制代碼 代碼如下:

Contract Class的定義:
    Contract Class,又可以叫做Companion Class。
    Android Developer的幫助文檔是這么說的:
   < A contract class is a container for constants that define names for URIs,
     tables, and columns. The contract class allows you to use the same constants
     across all the other classes in the same package. This lets you change a
     column name in one place and have it propagate throughout your code.>
     Contact 類是定義URI、表、列的名字的容器。這個類允許我們在同一包的不同類下使用相同的常量。
     我們在一處修改了列名,同時傳播到我們代碼的每個地方。

復(fù)制代碼 代碼如下:

package com.example.sqlitetest;
//Contract類
public class Contact {
   
    int _id;
    String _name;
    String _phone_number;
   
    public Contact(){
       
    }
    public Contact(int id, String name, String _phone_number){
        this._id = id;
        this._name = name;
        this._phone_number = _phone_number;
    }
   
    public Contact(String name, String _phone_number){
        this._name = name;
        this._phone_number = _phone_number;
    }
    public int getID(){
        return this._id;
    }
   
    public void setID(int id){
        this._id = id;
    }
   
    public String getName(){
        return this._name;
    }
   
    public void setName(String name){
        this._name = name;
    }
   
    public String getPhoneNumber(){
        return this._phone_number;
    }

    public void setPhoneNumber(String phone_number){
        this._phone_number = phone_number;
    }
}

2.使用SQLHelper創(chuàng)建數(shù)據(jù)庫

          就像保存文件在內(nèi)部存儲一樣,Android在私有的應(yīng)用存儲空間存儲我們的數(shù)據(jù)庫,這樣就保證我們的數(shù)據(jù)是安全的。不能被其他應(yīng)用訪問到。

在設(shè)備上存儲的數(shù)據(jù)庫保存在:
             /data/data/<package_name>/databases目錄下

為了使用SQLiteOpenHelper,我們需要創(chuàng)建一個重寫了onCreate(),onUpgrade()和onOpen()回調(diào)方法的子類。

3.數(shù)據(jù)的增刪改查

增:傳ContentValue值到insert()方法。

復(fù)制代碼 代碼如下:

SQLiteDatabase db = this.getWritableDatabase();
 
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
 
db.insert(TABLE_CONTACTS, null, values);
db.close();

刪:delete()方法

復(fù)制代碼 代碼如下:

SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
        new String[] { String.valueOf(contact.getID()) });
db.close();

 改:update()方法

 

復(fù)制代碼 代碼如下:

 SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());


return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
          ew String[] { String.valueOf(contact.getID()) });
 

查:query()方法

復(fù)制代碼 代碼如下:

SQLiteDatabase db = this.getReadableDatabase();

Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));

return contact;

完整DatabaseHelper代碼如下:

復(fù)制代碼 代碼如下:

package com.example.sqlitetest;

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

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

public class DatabaseHelper extends SQLiteOpenHelper {

    // 數(shù)據(jù)庫版本
    private static final int DATABASE_VERSION = 1;

    // 數(shù)據(jù)庫名
    private static final String DATABASE_NAME = "contactsManager";

    //Contact表名
    private static final String TABLE_CONTACTS = "contacts";

    //Contact表的列名
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // 創(chuàng)建表
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }

    // 更新表
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 刪除舊表
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

        //再次創(chuàng)建表
        onCreate(db);
    }

    /**
     *增刪改查操作
     */

    // 增加新的聯(lián)系人
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());

        // 插入行
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // 關(guān)閉數(shù)據(jù)庫的連接
    }

    // 獲取聯(lián)系人
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();

        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        return contact;
    }
   
    // 獲取所有聯(lián)系人
    public List<Contact> getAllContacts() {
        List<Contact> contactList = new ArrayList<Contact>();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;

        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                contactList.add(contact);
            } while (cursor.moveToNext());
        }

        return contactList;
    }

    // 更新單個聯(lián)系人
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());

        //更新行
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }

    // 刪除單個聯(lián)系人
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }


    // 獲取聯(lián)系人數(shù)量
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();

        return cursor.getCount();
    }
}

還有一些代碼不是本次學(xué)習(xí)的重點(diǎn),就不貼出來了。有需要的留言找我要。

 Demo運(yùn)行效果圖:

相關(guān)文章

最新評論

海门市| 济南市| 长岛县| 商都县| 德江县| 闽清县| 宜良县| 商城县| 兴仁县| 鄂州市| 莱阳市| 广水市| 枞阳县| 德昌县| 石家庄市| 财经| 江陵县| 正定县| 黄山市| 杨浦区| 新龙县| 凤冈县| 韩城市| 德昌县| 平潭县| 延庆县| 兴隆县| 房产| 西城区| 新巴尔虎左旗| 庆安县| 新巴尔虎左旗| 阳东县| 祁阳县| 湘潭市| 广丰县| 平乐县| 延边| 巢湖市| 承德市| 明水县|