Android 開發中使用 SQLite 數據庫

SQLite 介紹

  SQLite 一個很是流行的嵌入式數據庫,它支持 SQL 語言,而且只利用不多的內存就有很好的性能。html

    此外它仍是開源的,任何人均可以使用它。許多開源項目((Mozilla, PHP, Python)都使用了 SQLite.android

  SQLite 由如下幾個組件組成:SQL 編譯器、內核、後端以及附件。sql

  SQLite 經過利用虛擬機和虛擬數據庫引擎(VDBE),使調試、修改和擴展 SQLite 的內核變得更加方便。數據庫

 SQLite 內部結構編程

圖 1. SQLite 內部結構

 

原文 http://www.ibm.com/developerworks/cn/opensource/os-cn-sqlite/index.html  後端


 

 

SQLite的優勢:

  1. 輕量級

    使用 SQLite 只須要帶一個動態庫,就能夠享受它的所有功能, 並且那個動態庫的尺寸想當小。
  2. 獨立性

    SQLite 數據庫的核心引擎不須要依賴第三方軟件,也不須要所謂的「安裝」。
  3. 隔離性

    SQLite 數據庫中全部的信息(好比表、視圖、觸發器等) 都包含在一個文件夾內,方便管理和維護。
  4. 跨平臺

    SQLite 目前支持大部分操做系統,不至電腦操做系統更在衆多的手機系統 也是可以運行,好比:Android。
  5. 多語言接口

    SQLite 數據庫支持多語言編程接口。
  6. 安全性

    SQLite 數據庫經過數據庫級上的獨佔性和共享鎖來實現獨立事務處理。 這意味着多個進程能夠在同一時間從同一數據庫讀取數據, 但只能有一個能夠寫入數據。

 

 

 

在Android中鏈接SQLite須要先建立一個類,而且繼承個類extends SQLiteOpenHelper

package com.example.sqlite;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class MyOpenHelper extends SQLiteOpenHelper {

    /**
     * @param context    上下文
     * name: 數據庫的名字
     * factory 目的建立 cursor 對象
     * version 數據庫的版本  從1開始
     */
    public MyOpenHelper(Context context) {
        super(context, "itheima.db", null, 1);
//        super(context, name, factory, version);
    }

    /**
     * Called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
     * 當數據庫第一次建立的時候調用
     * 那麼這個方法特別適合作表結構的初始化    建立表就是寫 sql 語句
     */
    public void onCreate(SQLiteDatabase db) {
        // id 通常以  _d  下劃線開頭
        String  sql ="create table wx_user(" +
                "id int primary key," +
                "name varchar(30)," +
                "tou varchar(20)," +
                "content varchar(50)," +
                "dateTime varchar(30)" +
                ")";
      db.execSQL(sql);
    }

    /**
     * Called when the database needs to be upgraded. 
     * 當數據庫版本升級的時候調用
     * 這個方法適合作什麼    表結構的更新
     *  
     */
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("alter table info add phone varchar(20)");
    }

}
MyOpenHelper

 

 這裏建立了數據庫類,接下來是往數據庫中插入數據;數組

    //方法一
    // 建立數據庫
        MyOpenHelper helper = new MyOpenHelper(this);
        SQLiteDatabase db = helper.getWritableDatabase();

        // ContentValues 實際上是一個map 對象 google 工程師封裝的方法
        ContentValues values = new ContentValues();

        // 一一對應填充數據
     values.put("id",1);
        values.put("name", "android");
        values.put("tou", "xxx");
        values.put("content", "今天學習了SQLite");
        values.put("dateTime", "11月29號");

        db.insert("t_Message", null, values);
        // 方法二:使用sql 語句
        String sql = "insert into t_Message(id,name,tou,content,datetime) values(?,?,?,?,?)";
        //
        String[] sqlVales = {2, "oracle", "aaa", "oracle快忘記了", "11月20日" };
        db.execSQL(sql, sqlVales);
        // 關閉數據庫鏈接
        db.close();
插入數據一

 
// 方法三
//往數據庫中插入數據的代碼,在這裏使用的是execSQL(sql);
for(int i=3;i<20;i++){
            String sql = "insert into wx_user(id,name,tou,content,dateTime) values("+i+",'oracle"+i+"','aa','oracle是什麼','11月19日')";
            sqlDatabase.execSQL(sql);
}
插入數據三

 

往數據庫中參入數據以後,咱們再將數據庫中的數據取出來看看;咱們須要先建立一個實體類;

package com.example.entiy;

// 建立實體類
public class unserInFo { 
    private int id;
    private String name;
    private String dateTime;
    private String tou;
    private String content;
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getContent() {
        return content;
    }
    public void setContent(String content) {
        this.content = content;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getDateTime() {
        return datetime;
    }
    public void setDateTime(String dateTime) {
        this.dateTime= dateTime;
    }
    public String getTou() {
        return tou;
    }
    public void setTou(String tou) {
        this.tou = tou;
    }
    public String toString() {
        return "unserInFo [id="+id+,"name=" + name + ", dataTime=" + dataTime+ ", tou=" + tou+ "]";
    }
    public unserInFo() {
        super();
    }
    
}
建立實體類

 

獲取數據

//定義一個集合用來存放全部的結果
List<unserInFo> user = new ArrayList<unserInFo>();
//經過遊標來獲取表wx_user的信息,
Cursor c=sqlDatabase.query("wx_user", null, null, null, null, null, null);
        //先判斷是否有第一條數據(ic.moveToFirst()將遊標移到第一條數據,若是沒有第一條數據則返回false,不然返回true)
       if(c.moveToFirst()){
                //經過getCount()來決定循環的次數getCount()是遊標的總數量。
        for (int i = 0; i<c.getCount();i++) {
            unserInFo uif = new unserInFo();
            
            //將遊標移動到下一條數據
            c.moveToNext();
            uif.setId(c.getInt(c.getColumnIndex("id")));
            uif.setLastdate(c.getString(c.getColumnIndex("dateTime")));
            uif.setName(c.getString(c.getColumnIndex("name")));
            uif.setZhao(c.getString(c.getColumnIndex("tou")));
            uif.setContent(c.getString(c.getColumnIndex("content")));
            user.add(uif);
            
        }
}    
//最後數據庫中獲取到的數據就所有存放到user集合中了,咱們只須要遍歷user就能顯示數據了。
獲取數據

 

 

SQLiteOpenHelper是SQLiteDatabase的一個幫助類, 用來管理數據庫的建立和版本的更新。

通常是創建一個類繼承它,並實現它的onCreate和onUpgrade方法。 經常使用的方法有:

onCreate(SQLiteDatabase db)安全

建立數據庫時調用oracle

onUpgrade(SQLiteDatabase db,int oldVersion , int newVersion)app

版本更新時調用 

getReadableDatabase()

建立或打開一個只讀數據庫 

getWritableDatabase() 

建立或打開一個讀寫數據庫

 

 

 

 

 

 

 

1.SQLiteDatabase類

經常使用方法:

(int) delete(String table,String whereClause,String[] whereArgs)  刪除數據行的便捷方法

(long) insert(String table,String nullColumnHack,ContentValues values)

添加數據行的便捷方法

(int) update(String table, ContentValues values, String whereClause, String[] whereArgs)

更新數據行的便捷方法
(void) execSQL(String sql)

執行一個SQL語句,能夠是一個select或其餘的sql語句

(void) close() 關閉數據庫

(Cursor) query(String table, String[] columns, String selection,

  String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

查詢指定的數據表返回一個帶遊標的數據集

(Cursor) rawQuery(String sql, String[] selectionArgs)

運行一個預置的SQL語句,返回帶遊標的數據集

(與上面的語句最大的區別就是防止SQL注入)

 

 

 

 

 

 

 

 

 

 

 

2.SQLiteDatabase類

使用insert方法

ContentValues cv = new ContentValues();  // 實例化一個ContentValues用來裝載待插入的數據

cv.put("username","Jack Johnson");     // 添加用戶名

cv.put("password","iLovePopMusic");      // 添加密碼

db.insert("user",null,cv);            // 執行插入操做
實例化一個ContentValues

  

使用execSQL方式來實現

String sql = "insert into user(username,password) values ('Jack Johnson','iLovePopMuisc');  //插入操做的SQL語句

db.execSQL(sql);  //執行SQL語句
插入SQL語句

 

數據的刪除

String whereClause = "username=?";    // 刪除的條件

String[] whereArgs = {"Jack Johnson"};    // 刪除的條件參數

db.delete("user",whereClause,whereArgs);   // 執行刪除 

String sql = "delete from user where username='Jack Johnson'";  // 刪除操做的SQL語句

db.execSQL(sql);  // 執行刪除操做
刪除語句

 

數據修改

ContentValues cv = new ContentValues();      // 實例化

ContentValues cv.put("password","iHatePopMusic"); // 添加要更改的字段及內容

String whereClause = "username=?";        // 修改條件

String[] whereArgs = {"Jack Johnson"};        // 修改條件的參數

db.update("user",cv,whereClause,whereArgs);    // 執行修改 

String sql = "update [user] set password = 'iHatePopMusic' where username='Jack Johnson'";  // 修改的SQL語句

db.execSQL(sql);    // 執行修改
更改

 

數據查詢

經過query實現查詢的

public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit)

table

表名稱

column

列名稱數組

selection

條件子句,,至關於where 

selectionArgs

條件語句的參數數組

groupBy

分組

having

分組條件

orderBy

排序類

limit

分頁查詢的限制

Cursor

返回值,至關於結果集resultSet

 

 

 

 

 

 

 

 

 

 

 

 

 

 

遊標(Cursor)

getCount()

總記錄條數

isFirst()

判斷是否第一條記錄

isLast()

判斷是否最後一條記錄

moveToFirst()

移動到第一條記錄

moveToLast()

移動到最後一條記錄

move(int offset)

移動[是指偏移量而不是指移到指定位置]

moveToNext()

移動到嚇一條記錄

moveToPrevious()

移動到上一條記錄

getColumnIndex(String columnName)

得到指定列索引的int類型值

   

 

 

 

 

 

 

 

 

 

 

 

 

 

複製代碼
遊標(Cursor)
Cursor c = db.query("user",null,null,null,null,null,null);//查詢並得到遊標
if(c.moveToFirst()){//判斷遊標是否爲空
    for(int i=0;i<c.getCount();i++){
        c.moveToNext();
        String username = c.getString(c.getColumnIndex("username");
        String password = c.getString(c.getColumnIndex("password"));
    }
複製代碼

rawQuery實現的帶參數查詢

Cursor c = db.rawQuery("select * from user where username=?",new Stirng[]{"Jack Johnson"});
if(cursor.moveToFirst()) {
    String password = c.getString(c.getColumnIndex("password"));
}

 

   http://www.cnblogs.com/shanyou/archive/2007/01/08/615245.html  

相關文章
相關標籤/搜索