前段時間寫了個安卓平臺下SQLite數據庫操做的實例 ,一直沒得時間總結 ,今天把它弄出來了。javascript
在Android 運行時環境包含了完整的 SQLite。java
首先介紹一下SQLite這個數據庫:android
SQLite,是一款輕型的數據庫,是遵照ACID的關聯式數據庫管理系統,它的設計目標是嵌入式的,並且目前已經在不少嵌入式產品中使用了它,它佔用資源很是的低,在嵌入式設備中,可能只須要幾百K的內存就夠了。它可以支持Windows/Linux/Unix等等主流的操做系統,同時可以跟不少程序語言相結合,好比 Tcl、C#、PHP、Java等,還有ODBC接口,一樣比起Mysql、PostgreSQL這兩款開源世界著名的數據庫管理系統來說,它的處理速度比他們都快。sql
有一點相對其餘數據庫來講比較特殊的是:SQLite是無類型的. 這意味着你能夠保存任何類型的數據到你所想要保存的任何表的任何列中,意思就是說話你能夠在建立數據庫表的時候任意定義數據類型,卻不影響實際使用時的數據存儲。數據庫
舉個例子說就是你能夠在建立表時定義username字段爲varchar類型,可是實時使用時你能夠向這個字段存入一、2.五、2012-6-6.。。這樣的整型,單精,以及時間等其餘類型,在SQLite裏沒有這種限制。app
可是有一種狀況例外:當字段類型爲 」Integer Primary Key」 時,就是定義表主鍵,這個就只能是integer類型。和普通數據庫相同 。ide
SQLite 不支持一些標準的 SQL 功能,特別是外鍵約束(FOREIGN KEY constrains),嵌套 transcaction 和 RIGHT OUTER JOIN 和 FULL OUTER JOIN, 還有一些 ALTER TABLE 功能。工具
須要注意一點: SQLite不支持存儲過程!測試
我這裏就簡單介紹,如須要可自行去了解關於SQLite的更多知識,this
而後是個人Demo(一個簡單的完成數據庫增刪查改操做):
首先是項目目錄結構:
在本項目中咱們使用JUnit測試,就要在AndroidManifest.xml配置JUnit
AndroidManifest.xml
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="org.yzsoft.sqlitedemo.test"
- android:versionCode="1"
- android:versionName="1.0" >
-
- <!-- 爲了方便測試,我直接把上面包位置改爲我項目的測試包下 -->
- <uses-sdk
- android:minSdkVersion="8"
- android:targetSdkVersion="15" />
-
- <application
- android:icon="@drawable/ic_launcher"
- android:label="@string/app_name"
- android:theme="@style/AppTheme" >
-
- <!--
- 由於咱們開發項目的時候,包會比較多,因此最好在下面這個activity的配置( android:name="org.yzsoft.sqlitedemo.activity.MainActivity" )這句這裏打上完整的 包名.類名
- ,雖然能夠直接用 .類名,可是這個.類名是創建在
- <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.yzsoft.sqlitedemo.test"
- 之上的,用package+.類名也恰好能夠組合成完整路徑。可是咱們保險一點寫完整去。
- -->
- <activity
- android:name="org.yzsoft.sqlitedemo.activity.MainActivity"
- android:label="@string/title_activity_main" >
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
-
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <!-- JUnit要加這句 -->
- <uses-library android:name="android.test.runner" />
- </application>
- <!-- JUnit還要加這段 (android:targetPackage測試類所在包名 ) -->
- <instrumentation
- android:name="android.test.InstrumentationTestRunner"
- android:label="Test Unit Tests"
- android:targetPackage="org.yzsoft.sqlitedemo.test" >
- </instrumentation>
-
- </manifest>
一、MainActivity.java(由於本項目中使用JUnit進行測試,就不須要Activity了,留着不用寫它)
- package org.yzsoft.sqlitedemo.activity;
-
- import org.yzsoft.sqlitedemo.util.R;
- import org.yzsoft.sqlitedemo.util.R.layout;
- import org.yzsoft.sqlitedemo.util.R.menu;
-
- import android.os.Bundle;
- import android.app.Activity;
- import android.view.Menu;
-
- public class MainActivity extends Activity {
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_main);
- }
-
- @Override
- public boolean onCreateOptionsMenu(Menu menu) {
- getMenuInflater().inflate(R.menu.activity_main, menu);
- return true;
- }
- }
二、DBOpenHandler.java
- package org.yzsoft.sqlitedemo.util;
-
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteDatabase.CursorFactory;
- import android.database.sqlite.SQLiteOpenHelper;
-
- public class DBOpenHandler extends SQLiteOpenHelper {
-
-
- public DBOpenHandler(Context context, String name, CursorFactory factory, int version) {
- super(context, name, factory, version);
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
-
- db.execSQL("create table t_users(id integer primary key autoincrement,username varchar(200),pass varchar(200) )");
-
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
-
- }
-
- }
三、TUsers.java(實體類,習慣了WEB開發,總會加個實體類,方便)
- package org.yzsoft.sqlitedemo.vo;
-
- public class TUsers {
- private int id ;
- private String username;
- private String pass;
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- public String getPass() {
- return pass;
- }
- public void setPass(String pass) {
- this.pass = pass;
- }
- }
四、SQLiteDAOImpl.java(數據庫操做實現類)
- package org.yzsoft.sqlitedemo.util;
-
- import java.util.ArrayList;
- import java.util.List;
- import org.yzsoft.sqlitedemo.vo.TUsers;
-
- import android.content.Context;
- import android.database.Cursor;
- import android.database.sqlite.SQLiteDatabase;
-
- public class SQLiteDAOImpl {
- private DBOpenHandler dbOpenHandler;
-
- public SQLiteDAOImpl(Context context) {
- this.dbOpenHandler = new DBOpenHandler(context, "dbtest.db", null, 1);
- }
-
- public void save(TUsers tusers) {
- SQLiteDatabase db = dbOpenHandler.getWritableDatabase();
- db.execSQL("insert into t_users (username,pass) values(?,?)", new Object[] { tusers.getUsername(), tusers.getPass() });
- db.close();
- }
-
- public void delete(Integer id) {
- SQLiteDatabase db = dbOpenHandler.getWritableDatabase();
- db.execSQL("delete from t_users where id=?", new Object[] { id.toString() });
- db.close();
- }
-
- public void update(TUsers tusers) {
- SQLiteDatabase db = dbOpenHandler.getWritableDatabase();
- db.execSQL("update t_users set username=?,pass=? where" + " id=?", new Object[] { tusers.getUsername(), tusers.getPass(), tusers.getId() });
- db.close();
- }
-
- public TUsers find(Integer id) {
- TUsers tusers = null;
- SQLiteDatabase db = dbOpenHandler.getReadableDatabase();
-
- Cursor cursor = db.rawQuery("select * from t_users where id=?", new String[] { id.toString() });
- if (cursor.moveToFirst()) {
- tusers = new TUsers();
- tusers.setId(cursor.getInt(cursor.getColumnIndex("id")));
- tusers.setUsername(cursor.getString(cursor.getColumnIndex("username")));
- tusers.setPass(cursor.getString(cursor.getColumnIndex("pass")));
-
- }
- db.close();
- return tusers;
- }
-
- public List<TUsers> findAll() {
- List<TUsers> lists = new ArrayList<TUsers>();
- TUsers tusers = null;
- SQLiteDatabase db = dbOpenHandler.getReadableDatabase();
-
-
-
-
- Cursor cursor = db.rawQuery("select * from t_users ", null);
- while (cursor.moveToNext()) {
- tusers = new TUsers();
- tusers.setId(cursor.getInt(cursor.getColumnIndex("id")));
- tusers.setUsername(cursor.getString(cursor.getColumnIndex("username")));
- tusers.setPass(cursor.getString(cursor.getColumnIndex("pass")));
- lists.add(tusers);
- }
- db.close();
- return lists;
- }
-
- public long getCount() {
- SQLiteDatabase db = dbOpenHandler.getReadableDatabase();
- Cursor cursor = db.rawQuery("select count(*) from t_users ", null);
- cursor.moveToFirst();
- db.close();
- return cursor.getLong(0);
- }
-
- }
五、TUsersTest.java(JUnit測試類)
- package org.yzsoft.sqlitedemo.test;
-
- import java.util.List;
-
- import org.yzsoft.sqlitedemo.util.DBOpenHandler;
- import org.yzsoft.sqlitedemo.util.SQLiteDAOImpl;
- import org.yzsoft.sqlitedemo.vo.TUsers;
-
- import android.test.AndroidTestCase;
- import android.util.Log;
-
- public class TUsersTest extends AndroidTestCase {
- private static final String TAG = "這個是測試類";
-
- public void testCreate() {
- DBOpenHandler dbHandler = new DBOpenHandler(this.getContext(), "dbtest.db", null, 1);
- dbHandler.getWritableDatabase();
- }
-
- public void testSave() throws Throwable {
- SQLiteDAOImpl p = new SQLiteDAOImpl(this.getContext());
- TUsers tuser = new TUsers();
- tuser.setUsername("用戶");
- tuser.setPass("密碼");
- p.save(tuser);
- Log.i(TAG, "插入成功");
- }
-
- public void testUpate() throws Throwable {
- SQLiteDAOImpl p = new SQLiteDAOImpl(this.getContext());
- TUsers tuser = p.find(1);
- tuser.setUsername("張三");
- p.update(tuser);
- Log.i(TAG, "修改爲功");
- }
-
- public void testDelete() throws Throwable {
- SQLiteDAOImpl p = new SQLiteDAOImpl(this.getContext());
- p.delete(2);
- Log.i(TAG, "刪除成功");
- }
-
- public void testFind() throws Throwable {
- SQLiteDAOImpl p = new SQLiteDAOImpl(this.getContext());
- TUsers tuser = p.find(1);
- Log.i(TAG, tuser.getUsername() + " 用戶名");
- }
-
- public void testGetCount() throws Throwable {
- SQLiteDAOImpl p = new SQLiteDAOImpl(this.getContext());
- Log.i(TAG, p.getCount() + " 總記錄數");
- }
-
- public void testFindAll() throws Throwable {
- SQLiteDAOImpl p = new SQLiteDAOImpl(this.getContext());
- List<TUsers> tusers = p.findAll();
- for (TUsers tuser : tusers) {
- Log.i(TAG, tuser.getUsername() + " 用戶名");
- }
- }
- }
而後是測試中的一些截圖:
最後咱們把File Exploer中data/data/項目包名/databases/dbtest.db 導出來,用Navicat Premium等數據庫管理工具查看裏面的數據:
導出來看看:
雖然安卓平臺中SQLite是個小型的本地數據庫,可是有些地方使用起來會比文件存儲更方便,本文只是對它做一個簡單的操做實例 ,有這方面興趣的童鞋能夠本身去深刻研究。也但願你們能多交流交流~~~~
最最後~附上項目源碼: