Android使用的是SQLite数据库系统。为一人应用程序所创建的数据库只能被此应用程序访问,其他应用程序将不能访问它。以编程方式创建的SQLite数据库总是存储在/data/data/<package_name>/databases文件夹下。
一、创建数据库辅助类
package com.example.androidtest; 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; /** * 访问数据库的辅助类 * 封装了访问数据的所有复杂性。 * 为一个应用程序所创建的数据库只能被此应用程序访问,其他应用程序将不能访问它。 * 数据库文件存储在/data/data/<package_name>/databases文件夹下。 * @author Administrator * */ 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; //定义创建表的sql语句常量 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); } } /** * 创建or打开数据库 * @return * @throws SQLException */ public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } /** * 关闭数据库 */ public void close() { DBHelper.close(); } /** * 插入数据 * @param name * @param email * @return ID */ 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); } /** * 删除数据 * @param rowId * @return true:删除成功 */ public boolean deleteContact(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID+"="+rowId, null) > 0; } /** * 查询所有数据 * @return Cursor 游标(可看成指向结果集的指针) */ public Cursor getAllContacts() { String[] columns = new String[] {KEY_ROWID, KEY_NAME, KEY_EMAIL}; return db.query(DATABASE_TABLE, columns, null, null, null, null, null); } /** * 查询指定数据 * @param rowId * @return Cursor 游标(可看成指向结果集的指针) * @throws SQLException */ public Cursor getContact(long rowId) throws SQLException { String[] columns = new String[] {KEY_ROWID, KEY_NAME, KEY_EMAIL}; Cursor mCursor = db.query(true, DATABASE_TABLE, columns, KEY_ROWID+"="+rowId, null, null, null, null, null); if(mCursor != null) { mCursor.moveToFirst(); } return mCursor; } /** * 更新指定数据 * @param rowId * @param name * @param email * @return true:更新成功 */ 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; } }
二、创建活动
视图
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" tools:context="${relativePackage}.${activityClass}" > <Button android:id="@+id/btn_insert" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Insert" android:onClick="onClickInsert" /> <Button android:id="@+id/btn_query_all" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Query all" android:onClick="onClickQueryAll" /> <Button android:id="@+id/btn_query_id" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Query id" android:onClick="onClickQueryID" /> <Button android:id="@+id/btn_update" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Update" android:onClick="onClickUpdate" /> <Button android:id="@+id/btn_delete" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delete" android:onClick="onClickDelete" /> </LinearLayout>
代码
package com.example.androidtest; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Toast; public class DatabasesActivity extends Activity { DBAdapter db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_databases); db = new DBAdapter(this); db.open(); } @Override protected void onDestroy() { super.onDestroy(); db.close(); } public void onClickInsert(View view) { Log.d("test", "db="+db); long id = db.insertContact("Wei-MengLee", "weimenglee@qq.com"); id = db.insertContact("Mary Jackson", "mary@qq.com"); Toast.makeText(this, "Insert successful", Toast.LENGTH_SHORT).show(); } public void onClickQueryAll(View view) { Cursor c = db.getAllContacts(); if(c.moveToFirst()){ do { DisplayContact(c); } while (c.moveToNext()); } } public void onClickQueryID(View view) { Cursor c = db.getContact(2); if(c.moveToFirst()){ DisplayContact(c); }else{ Toast.makeText(this, "No contact found", Toast.LENGTH_SHORT).show(); } } public void onClickUpdate(View view) { if(db.updateContact(1, "Wei-Meng Lee", "weimenglee@gmail.com")){ Toast.makeText(this, "Update successful", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this, "Update failed", Toast.LENGTH_SHORT).show(); } } public void onClickDelete(View view) { if(db.deleteContact(1)){ Toast.makeText(this, "Delete successful", Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(this, "Delete failed", Toast.LENGTH_SHORT).show(); } } public void DisplayContact(Cursor c) { Toast.makeText(this, "id: "+c.getString(0) + "\n" + "Name: "+c.getString(1) + "\n" + "Email: " + c.getString(2), Toast.LENGTH_SHORT).show(); } /** * 把assets目录下的一个现成sqlite文件复制到目标文件夹。 * 注意: assets目录下的文件必须采用小写字母格式。 */ public void CopyMyDB() { try { String destPath = "/data/data/"+getPackageName()+"/databases"; File f = new File(destPath); Log.d("test", "db path="+f.getAbsolutePath()); if (!f.exists()){ f.mkdir(); f.createNewFile(); CopyDB(getBaseContext().getAssets().open("mydb"), new FileOutputStream(destPath+"/MyDB")); } } catch (FileNotFoundException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } } public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException { byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } inputStream.close(); outputStream.close(); } }
运行效果