1.Android中通过SQLite数据库引擎来实现结构化数据存储。SQLite是一个嵌入式数据库引擎,针对内存等资源有限的设备,提供的是一种高效的数据库引擎。
Android中操作数据库首先要通过一个 类:android.database.sqlite.SQLiteOpenHelper。它封装了如何打开一个数据库,其中当然也包含如果数据库不存在 就创建这样的逻辑。看一个例子:
1 pubilc class DatabaseHelper extends SQLiteOpenHelper {
2 private static final String DATABASE_NAME = " com.roiding.simple.note " ;
3 private static final int DATABASE_VERSION = 1 ;
4 private static final String NOTES_TABLE_NAME = " notes " ;
5
6 DatabaseHelper(Context context) {
7 super (context, DATABASE_NAME, null , DATABASE_VERSION);
8 }
9
10 @Override
11 public void onCreate(SQLiteDatabase db) {
12 db.execSQL( " CREATE TABLE " + NOTES_TABLE_NAME
13 + " (id integer primary key autoincrement, name text); " );
14 }
15
16 @Override
17 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
18 db.execSQL( " DROP TABLE IF EXISTS notes " );
19 onCreate(db);
20 }
21 }
这里面,如下的语句需要解释:
在Android中,数据库存放在 /data/data/PACKAGE_NAME/databases 目录下。
接下来就可以使用这个Helper来操作数据库了,操作数据库也就无非是增、删、改、查。先看一个增的例子:
1 public static void insert(Context context, String s) {
2 DatabaseHelper mOpenHelper = new DatabaseHelper(context);
3
4 String table = " notes " ;
5 String nullColumnHack = " id " ;
6
7 ContentValues values = new ContentValues();
8 values.put( " name " , " www.roiding.com " );
9
10 long id = mOpenHelper.getReadableDatabase().insert(table,
11 nullColumnHack, values);
12
13 mOpenHelper.getReadableDatabase().close();
14 }
再看一个查的例子:
1 public static void select (Context context) {
2 DatabaseHelper mOpenHelper = new DatabaseHelper(context);
3
4 String table = "notes";
5 String [] columns = new String [] { "id", "name" };
6 String selection = "id > ? and name <> ?";
7 String [] selectionArgs = new String [] { " 0 ", "roiding.com" };
8 String groupBy = null ;
9 String having = null ;
10 String orderBy = "id desc ";
11 String limit = " 1 ";
12
13 Cursor c = mOpenHelper.getReadableDatabase().query( table ,
14 columns, selection, selectionArgs, groupBy, having , orderBy, limit);
15
16 c.moveToFirst();
17 for ( int i = 0 ; i < c.getCount(); i ++ ) {
18 String s = c.getString( 1 );
19 c.moveToNext();
20 }
21 c. close ();
22 mOpenHelper.getReadableDatabase(). close ();
23 }
再看一个删除和修改的例子:
1 public static void delete(Context context) {
2 DatabaseHelper mOpenHelper = new DatabaseHelper(context);
3
4 String table = " notes " ;
5 String selection = " id>? and name<>? " ;
6 String[] selectionArgs = new String[] { " 0 " , " roiding.com " };
7 String whereClause = selection;
8 String[] whereArgs = selectionArgs;
9
10 mOpenHelper.getWritableDatabase().delete(table, whereClause, whereArgs);
11 mOpenHelper.getWritableDatabase().close();
12 }
有了上面的基础这里就容易理解了,这里的whereClause相当于前面的selection,whereArgs相当于前面的selectionArgs。
1 public static void update(Context context) {
2 DatabaseHelper mOpenHelper = new DatabaseHelper(context);
3
4 String table = " notes " ;
5 String selection = " id>? and name<>? " ;
6 String[] selectionArgs = new String[] { " 0 " , " roiding.com " };
7 String whereClause = selection;
8 String[] whereArgs = selectionArgs;
9
10 ContentValues values = new ContentValues();
11 values.put( " name " , " www.roiding.com " );
12
13 mOpenHelper.getWritableDatabase().update(table, values,
14 whereClause, whereArgs);
15 mOpenHelper.getWritableDatabase().close();
16 }
这个update的用法,综合select和delete就可以理解。
注意:
在真实的应用中,会对上面这些基本操作做更高一级的抽象和封装,使之更容易使用。在select时,除了用上述的方法,将分段的SQL语句传进去之外,Android还支持一种方法:使用SQLiteQueryBuilder。如果使用的是上述的分段SQL语句的方法,在Android的内部实现中,也是先将分段的SQL使用SQLiteQueryBuilder的静态方法来生成一个真正的SQL的,而且,我没有看出来使用SQLiteQueryBuilder的优势。
Chapter09_Data_03/src/com/amaker/test/MainActivity.java
1 package com.amaker.test;
2
3 import android.app.Activity;
4 import android.content.ContentValues;
5 import android.database.Cursor;
6 import android.database.sqlite.SQLiteDatabase;
7 import android.os.Bundle;
8
9 public class MainActivity extends Activity {
10 @Override
11 public void onCreate(Bundle savedInstanceState) {
12 super .onCreate(savedInstanceState);
13 setContentView(R.layout.main);
14
15 SQLiteDatabase db = createDatabase();
16 // createTable(db);
17 // insert(db);
18 // insert2(db);
19 // update(db);
20 // update2(db);
21 // delete(db);
22 delete2(db);
23 query(db);
24 db.close();
25
26 }
27 // 创建数据库,注意这里要指定全路径
28 private SQLiteDatabase createDatabase(){
29 return SQLiteDatabase.openOrCreateDatabase( " /data/data/com.amaker.test/databases/temp2.db " , null );
30 }
31 // 创建表
32 private void createTable(SQLiteDatabase db){
33 String sql = " create table UserTbl(_id integer primary key autoincrement,username text,password text) " ;
34 db.execSQL(sql);
35 }
36 // 插入数据
37 private void insert(SQLiteDatabase db){
38 String sql = " insert into UserTbl(username,password) values('amaker','123') " ;
39 db.execSQL(sql);
40 }
41 // 插入2
42 private void insert2(SQLiteDatabase db){
43 ContentValues cv = new ContentValues();
44 cv.put( " username " , " ghz " );
45 cv.put( " password " , " 456 " );
46 db.insert( " UserTbl " , null , cv);
47 }
48 // 查询
49 private void query(SQLiteDatabase db){
50 Cursor c = db.query( " UserTbl " , null , null , null , null , null , null );
51 if (c.moveToFirst()){
52 for ( int i = 0 ; i < c.getCount(); i ++ ) {
53 c.move(i);
54 int id = c.getInt( 0 );
55 String username = c.getString( 1 );
56 String password = c.getString( 2 );
57 System.out.println(id + " : " + username + " : " + password);
58 }
59 }
60 }
61 // 修改
62 private void update(SQLiteDatabase db){
63 String sql = " update UserTbl set password=888 where _id=1 " ;
64 db.execSQL(sql);
65 }
66 // 修改2
67 private void update2(SQLiteDatabase db){
68 ContentValues values = new ContentValues();
69 values.put( " password " , " 999 " );
70 String whereClause = " _id=? " ;
71 String[] whereArgs = {String.valueOf( 1 )};
72 db.update( " UserTbl " , values, whereClause, whereArgs);
73 }
74
75 // 删除
76 private void delete(SQLiteDatabase db){
77 String sql = " delete from UserTbl where _id=2 " ;
78 db.execSQL(sql);
79 }
80 // 删除2
81 private void delete2(SQLiteDatabase db){
82 String whereClause = " _id=? " ;
83 String[] whereArgs = {String.valueOf( 1 )};
84 db.delete( " UserTbl " , whereClause, whereArgs);
85 }
86
87 }
Chapter09_Data_03/res/layout/main.xml
1 <? xml version = " 1.0 " encoding = " utf-8 " ?>
2 < LinearLayout xmlns:android = " http://schemas.android.com/apk/res/android "
3 android:orientation = " vertical "
4 android:layout_width = " fill_parent "
5 android:layout_height = " fill_parent "
6 >
7 < TextView
8 android:layout_width = " fill_parent "
9 android:layout_height = " wrap_content "
10 android:text = " @string/hello "
11 />
12 </ LinearLayout >
Chapter09_Data_03/AndroidManifest.xml
1 <? xml version = " 1.0 " encoding = " utf-8 " ?>
2 < manifest xmlns:android = " http://schemas.android.com/apk/res/android "
3 package = " com.amaker.test "
4 android:versionCode = " 1 "
5 android:versionName = " 1.0 " >
6 < application android:icon = " @drawable/icon " android:label = " @string/app_name " >
7 < activity android:name = " .MainActivity "
8 android:label = " @string/app_name " >
9 < intent - filter >
10 < action android:name = " android.intent.action.MAIN " />
11 < category android:name = " android.intent.category.LAUNCHER " />
12 </ intent - filter >
13 </ activity >
14
15 </ application >
16 < uses - sdk android:minSdkVersion = " 3 " />
17
18 </ manifest >