在Android中建立
和运用
数据库[多图]
2009-10-14 10:20:03 出处:https://www.yqdown.com
每个使用
程序都要运用
数据,Android使用
程序也不例外,Android运用
开源的、与操作系统无关的SQL数据库--SQLite,本文介绍的就是如何
为你的Android使用
程序建立
和操作SQLite数据库。
数据库支持每个使用
程序无论大小的生命线,除非你的使用
程序只处理基本
的数据,那么就须要
一个数据库系统存储你的结构化数据,Android运用
SQLite数据库,它是一个开源的、支持多操作系统的SQL数据库,在许多领域广泛运用
,如Mozilla FireFox就是运用
SQLite来存储配置数据的,iPhone也是运用
SQLite来存储数据的。
在Android中,你为某个使用
程序建立
的数据库,只有它可以访问,其它使用
程序是不能访问的,数据库位于Android设备/data/data//databases文件夹中,在这篇文章中,你将会学习到如何
在Android中建立
和运用
数据库。
SQLite数据库
运用
Eclipse建立
一个Android项目,取名为Database,如图1所示:
图1 数据库-运用
Eclipse建立
你的Android新项目
建立
DBAdapter辅助类
操作数据库的最佳实践是建立
一个辅助类,由它封装所有对数据库的复杂访问,对于调用代码而言它是透明的,因此我建立
了一个DBAdapter的辅助类,由它建立
、打开、关上
和运用
SQLite数据库。
首先,在src/
文件夹(在这个例子中是src/net.learn2develop.Database)下添加一个DBAdapter.java文件。
在DBAdapter.java文件中,导入所有你要运用
到的命名空间:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->package net.learn2develop.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 { }
接下来建立
一个数据库,取名为bookstitles,字段如图2所示。
图2 数据库字段
在DBAdapter.java文件中,定义清单1中的常量。
清单1 定义DBAdapter.java文件中的常量
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->package net.learn2develop.Database; 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 { public static final String KEY_ROWID = "_id"; public static final String KEY_ISBN = "isbn"; public static final String KEY_TITLE = "title"; public static final String KEY_PUBLISHER = "publisher"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "books"; private static final String DATABASE_TABLE = "titles"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table titles (_id integer primary key autoincrement, " + "isbn text not null, title text not null, " + "publisher text not null);"; private final Context context; }
DATABASE_CREATE常量包括建立
titles表的SQL语句。
在DBAdapter类中,你可以扩展SQLiteOpenHelper类,它是一个Android辅助类,主要用于数据库建立
和版本管理。实际上,你可以覆盖onCreate()和onUpgrade()要领
,如清单2所示。
清单2 在DBAdapter类中,扩展SQLiteOpenHelper类覆盖onCreate() 和 onUpgrade()要领
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> package net.learn2develop.Database; 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 { public static final String KEY_ROWID = "_id"; public static final String KEY_ISBN = "isbn"; public static final String KEY_TITLE = "title"; public static final String KEY_PUBLISHER = "publisher"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "books"; private static final String DATABASE_TABLE = "titles"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table titles (_id integer primary key autoincrement, " + "isbn text not null, title text not null, " + "publisher text not null);"; private final Context context; private DatabaseHelper DBHelper; private 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) { db.execSQL(DATABASE_CREATE); } @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 titles"); onCreate(db); } } }
onCreate()要领
建立
一个新的数据库,onUpgrade()要领
用于升级数据库,这可以通过检查DATABASE_VERSION常量定义的值来实现,对于onUpgrade()要领
而言,只不过是基本
地删除表,然后在建立
表而已。
现在你可以定义不同的要领
来打开和关上
数据库,如清单3中的添加/编辑/删除/行的函数。
清单3 定义打开和关上
数据库以及添加
/编辑/删除表中行的要领
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public class DBAdapter { //... //... //---打开数据库--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---关上
数据库--- public void close() { DBHelper.close(); } //---向数据库插入一个标题--- public long insertTitle(String isbn, String title, String publisher) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_ISBN, isbn); initialValues.put(KEY_TITLE, title); initialValues.put(KEY_PUBLISHER, publisher); return db.insert(DATABASE_TABLE, null, initialValues); } //---删除一个指定的标题--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---检索所有标题--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_ISBN, KEY_TITLE, KEY_PUBLISHER}, null, null, null, null, null); } //---检索一个指定的标题--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_ISBN, KEY_TITLE, KEY_PUBLISHER }, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---更新一个标题--- public boolean updateTitle(long rowId, String isbn, String title, String publisher) { ContentValues args = new ContentValues(); args.put(KEY_ISBN, isbn); args.put(KEY_TITLE, title); args.put(KEY_PUBLISHER, publisher); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } }
留心
Android运用
Cursor类返回一个须要
的值,Cursor作为一个指针从数据库查询返回结果集,运用
Cursor允许Android更有效地管理它们须要
的行和列,你运用
ContentValues对象存储键/值对,它的put()要领
允许你插入不同数据类型的键值。
清单4显示了完整的DBAdapter.java源代码。
清单4 DBAdapter.java完整源代码
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> package net.learn2develop.Database; 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 { public static final String KEY_ROWID = "_id"; public static final String KEY_ISBN = "isbn"; public static final String KEY_TITLE = "title"; public static final String KEY_PUBLISHER = "publisher"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "books"; private static final String DATABASE_TABLE = "titles"; private static final int DATABASE_VERSION = 1; private static final String DATABASE_CREATE = "create table titles (_id integer primary key autoincrement, " + "isbn text not null, title text not null, " + "publisher text not null);"; private final Context context; private DatabaseHelper DBHelper; private 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) { db.execSQL(DATABASE_CREATE); } @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 titles"); onCreate(db); } } //---打开数据库--- public DBAdapter open() throws SQLException { db = DBHelper.getWritableDatabase(); return this; } //---关上
数据库--- public void close() { DBHelper.close(); } //---向数据库中插入一个标题--- public long insertTitle(String isbn, String title, String publisher) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_ISBN, isbn); initialValues.put(KEY_TITLE, title); initialValues.put(KEY_PUBLISHER, publisher); return db.insert(DATABASE_TABLE, null, initialValues); } //---删除一个指定标题--- public boolean deleteTitle(long rowId) { return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //---检索所有标题--- public Cursor getAllTitles() { return db.query(DATABASE_TABLE, new String[] { KEY_ROWID, KEY_ISBN, KEY_TITLE, KEY_PUBLISHER}, null, null, null, null, null); } //---检索一个指定标题--- public Cursor getTitle(long rowId) throws SQLException { Cursor mCursor = db.query(true, DATABASE_TABLE, new String[] { KEY_ROWID, KEY_ISBN, KEY_TITLE, KEY_PUBLISHER }, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } //---更新一个标题--- public boolean updateTitle(long rowId, String isbn, String title, String publisher) { ContentValues args = new ContentValues(); args.put(KEY_ISBN, isbn); args.put(KEY_TITLE, title); args.put(KEY_PUBLISHER, publisher); return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } }
运用
数据库
现在你已经可以运用
建立
的辅助类来运用
数据库了,在DatabaseActivity.java文件中,建立
一个DBAdapter类的实例:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> package net.learn2develop.Database; import android.app.Activity; import android.os.Bundle; public class DatabaseActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DBAdapter db = new DBAdapter(this); } }
添加
一个标题
如果想在titles表中添加
一个标题,可以运用
DBAdapter类的insertTitle()要领
:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DBAdapter db = new DBAdapter(this); //---add 2 titles--- db.open(); long id; id = db.insertTitle( "0470285818", "C# 2008 Programmer's Reference", "Wrox"); id = db.insertTitle( "047017661X", "Professional Windows Vista
Gadgets Programming", "Wrox"); db.close(); }
insertTitle()要领
返回插入行的ID,如果在添加流程
中遇到不正确
,它就返回-1。
如果你分析Android设备/模拟器的文件系统,你可以看到book数据库建立
在database文件夹下,如图3所示。
图3 database文件夹
检索所有标题
想要检索titles表中的所有标题,可以运用
DBAdapter类的getAllTitles()要领
,如清单5所示。
清单5 运用
DBAdapter类的getAllTitles()要领
检索titles表中的所有标题
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->package net.learn2develop.Database; import android.app.Activity; import android.database.Cursor; import android.os.Bundle; import android.widget.Toast; public class DatabaseActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DBAdapter db = new DBAdapter(this); //---获取所有标题--- db.open(); Cursor c = db.getAllTitles(); if (c.moveToFirst()) { do { DisplayTitle(c); } while (c.moveToNext()); } db.close(); } }
返回的结果是一个Cursor对象,如果要显示所有标题,你首先应该调用Cursor对象的moveToFirst()要领
,如果它成功(意味着至少有一行有效),运用
DisplayTitle()要领
显示细致
的标题,要移动到下一个标题,可以调用Cursor对象的moveToNext()要领
,下面是DisplayTitle()要领
的定义:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public void DisplayTitle(Cursor c) { Toast.makeText(this, "id: " + c.getString(0) + "\n" + "ISBN: " + c.getString(1) + "\n" + "TITLE: " + c.getString(2) + "\n" + "PUBLISHER: " + c.getString(3), Toast.LENGTH_LONG).show(); }
图4显示Toast类,它从数据库中检索并显示一个标题。
图4 Toast类
检索单个标题
想要通过ID检索单个标题,可以运用
DBAdapter类的getTitle()要领
:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DBAdapter db = new DBAdapter(this); //---get a title--- db.open(); Cursor c = db.getTitle(2); if (c.moveToFirst()) DisplayTitle(c); else Toast.makeText(this, "No title found", Toast.LENGTH_LONG).show(); db.close(); }
返回的结果是一个Cursor对象,如果返回一行,可以运用
DisplayTitle()要领
显示标题的细致
信息,否则就运用
Toast类显示一个不正确
消息。
更新一个标题
要更新一个特定的标题,可以调用DBAdapter的updateTitle()要领
,传递想要更新的标题的ID给它就可以了,如清单6所示。
清单6 调用DBAdapter类的updateTitle()要领
更新标题
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DBAdapter db = new DBAdapter(this); //---更新标题--- db.open(); if (db.updateTitle(1, "0470285818", "C# 2008 Programmer's Reference", "Wrox Press")) Toast.makeText(this, "Update successful.", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Update failed.", Toast.LENGTH_LONG).show(); //------------------- //---检索相同的标题--- Cursor c = db.getTitle(1); if (c.moveToFirst()) DisplayTitle(c); else Toast.makeText(this, "No title found", Toast.LENGTH_LONG).show(); //------------------- db.close(); }
如果更新成功会显示一条表示成功的消息,同时,你可以检索刚刚更新的标题看更新结果能不能
正确。
删除一个标题
想要删除一个标题,可以调用DBAdapter类的deleteTitle()要领
,传递你想要删除的标题的ID即可:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/--> @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); DBAdapter db = new DBAdapter(this); //---delete a title--- db.open(); if (db.deleteTitle(1)) Toast.makeText(this, "Delete successful.", Toast.LENGTH_LONG).show(); else Toast.makeText(this, "Delete failed.", Toast.LENGTH_LONG).show(); db.close(); }
如果删除成功会显示一条表示成功的消息。
升级数据库
要升级数据库,修改DBAdapter类中DATABASE_VERSION常量的值比之前的值大,如之前的值是1,将其改为2:
Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->public class DBAdapter { public static final String KEY_ROWID = "_id"; public static final String KEY_ISBN = "isbn"; public static final String KEY_TITLE = "title"; public static final String KEY_PUBLISHER = "publisher"; private static final String TAG = "DBAdapter"; private static final String DATABASE_NAME = "books"; private static final String DATABASE_TABLE = "titles"; //---change this to a higher value--- private static final int DATABASE_VERSION = 2; private static final String DATABASE_CREATE = "create table titles (_id integer primary key autoincrement, " + "isbn text not null, title text not null, " + "publisher text not null);";
当你再次运行这个使用
程序时,你会在Eclipse的LogCat窗口中看到数据库已经升级的消息,如图5所示。
图5 LogCat窗口-消息显示数据库升级成功
简化数据库访问
运用
DBAdapter类,可以简化你的Android使用
程序访问数据库记录的操作,一个主要
的事情是在Android中建立
的SQLite数据库只有建立
它的使用
程序可以访问它。如果你要共享数据,你须要
运用
一个内容提供器,这个将在以后的文章中再介绍了。
分享到