1.为当前应用创建的数据库只能被自己访问,别的应用无法访问它;
2.数据库文件被储存在/data/data/<package_name>/databases文件夹下;
===========================================================================
3.创建DBAdapter Helper 类:
处理数据库相关操作的好习惯是创建一个帮手类来封装所有的访问数据库的复杂操作,是的调用代码是透明的。
所以,这里创建一个名为DBAdapter的帮手类,用来创建、打开、关闭和使用SQLite数据库。
这里,创建一个名叫MyDB的数据库,包含一个名叫contacts(联系人)的表。该表还有三列:_id,name,email.
先看代码:
package com.example.databases;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
static final String KEY_ROWID = "_id";
static final String KEY_NAME = "name";
static final String KEY_EMAIL = "email";
static final String TAG = "DBAdapter";
static final String DATABASE_NAME = "MyDB";
static final String DATABASE_TABLE = "contacts";
static final int DATABASE_VERSION = 1;
static final String DATABASE_CREATE = "create table contacts (_id integer primary key autoincrement, "
+ "name text not null, email text not null);";
final Context context;
DatabaseHelper DBHelper;
SQLiteDatabase db;
public DBAdapter(Context ctx) {
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL(DATABASE_CREATE);
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
}
// ---opens the database---
public DBAdapter open() throws SQLException {
db = DBHelper.getWritableDatabase();
return this;
}
// ---closes the database---
public void close() {
DBHelper.close();
}
// ---insert a contact into the database---
public long insertContact(String name, String email) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_EMAIL, email);
return db.insert(DATABASE_TABLE, null, initialValues);
}
// ---deletes a particular contact---
public boolean deleteContact(long rowId) {
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
}
// ---retrieves all the contacts---
public Cursor getAllContacts() {
return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_NAME,
KEY_EMAIL }, null, null, null, null, null);
}
// ---retrieves a particular contact---
public Cursor getContact(long rowId) throws SQLException {
Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] {
KEY_ROWID, KEY_NAME, KEY_EMAIL }, KEY_ROWID + "=" + rowId,
null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
// ---updates a contact---
public boolean updateContact(long rowId, String name, String email) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_EMAIL, email);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0;
}
}
分部分来看:
一.在DBAdapter中,加入一个继承自SQLiteOpenHelper类的私有类。在这个类中Android管理数据库的创建和升级。
你需要重写onCreate()和onUpgrade()方法:
二.数据库创建好后就可以进行增、删、改、查、打开、关闭操作。
注意Android使用Cursor类来作为查询的返回值。可以把Cursor看成是指向查询返回结果集的指针。
可以使用ContentValues对象来储存键值对。它的put()方法让你可以将不通数据类型的值插入键中;
在应用中用DBAdapter创建数据库时,你可以创建一个DBAdapter的实例:
public DBAdapter(Context ctx) { this.context = ctx; DBHelper = new DatabaseHelper(context); }
然后,这个构造函数就会创建一个DatabaseHelper的实例来创建一个数据库。
========================================================================================
4.程序化地使用数据库:
在DBAdapter的帮助下,就可以进行常用的数据库操作。
private void addContact(String name, String email)
{
db.open();
long id = db.insertContact(name, email);
if (id == -1 ) {
Toast.makeText(getBaseContext(), "Add contact failed.Try again", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getBaseContext(), "Add successfully.The row ID is" + id, Toast.LENGTH_SHORT).show();
}
db.close();
}
private void deleteContact(long ID)
{
db.open();
if (db.deleteContact(ID))
Toast. makeText (this, "Delete successful.", Toast. LENGTH_LONG).show();
else
Toast. makeText (this, "Delete failed.", Toast. LENGTH_LONG).show();
db.close();
}
private void retrieveAllContacts()
{
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst())
{
do {
Toast.makeText (this,
"id: " + c.getString(0) + "\n" +
"Name: " + c.getString(1) + "\n" +
"Email: " + c.getString(2),
Toast.LENGTH_LONG).show();
} while (c.moveToNext());
}
db.close();
}
private void retrieveSingleContact(long id)
{
db.open();
Cursor c = db.getContact(id);
Toast.makeText (this,
"id: " + c.getString(0) + "\n" +
"Name: " + c.getString(1) + "\n" +
"Email: " + c.getString(2),
Toast.LENGTH_LONG).show();
db.close();
}
private void updateAContact(int id, String name, String email)
{
db.open();
db.updateContact(id, name, email);
db.close();
}
=========================================================================================