知識點:
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類呢?
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()方法。
刪:delete()方法
改:update()方法
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()方法
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代碼如下:
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í)的重點,就不貼出來了。有需要的留言找我要。
Demo運行效果圖:
新聞熱點
疑難解答
圖片精選