【Android資料存放區】SQLite使用執行個體(附源碼)(轉載)

來源:互聯網
上載者:User

標籤:

原文地址:http://blog.csdn.net/wirelessqa/article/details/8583101 java當中提供了相當多的封裝好的類來執行對SqlLite的操作,如: SQLiteDatabase 作為資料庫操作的類,類似於C#當中我們自己寫的helper,PS(java對此還真是高度封裝) SQLiteOpenHelper 作為作為維護和管理資料庫的基類
執行個體: 會員資訊管理

功能:1.查看資料庫 2.清空資料庫 3.增加會員 4.刪除會員 5.更新會員 6.尋找會員

DBHelper類繼承自SQLiteOpenHelper

package com.wirelessqa.sqlite;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;import android.util.Log;/** * DBHelper繼承了SQLiteOpenHelper,作為維護和管理資料庫的基類 * @author bixiaopeng 2013-2-16 下午3:05:52 */public class DBHelper  extends SQLiteOpenHelper{    //final成員變數是常量 只能賦值一次    public static final String DB_NAME = "wirelessqa.db";    public static final String DB_TABLE_NAME = "info";    private static final int DB_VERSION=1;    public DBHelper(Context context) {        //Context context, String name, CursorFactory factory, int version        //factory輸入null,使用預設值        super(context, DB_NAME, null, DB_VERSION);    }    //資料第一次建立的時候會調用onCreate    @Override    public void onCreate(SQLiteDatabase db) {                //建立表          db.execSQL("CREATE TABLE IF NOT EXISTS info" +                      "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, website STRING,weibo STRING)");          Log.i(WirelessQA.TAG, "create table");    }    //資料庫第一次建立時onCreate方法會被調用,我們可以執行建立表的語句,    //當系統發現版本變化之後,會調用onUpgrade方法,我們可以執行修改表結構等語句    @Override    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        //在表info中增加一列other        //db.execSQL("ALTER TABLE info ADD COLUMN other STRING");          Log.i("WIRELESSQA", "update sqlite "+oldVersion+"---->"+newVersion);    }    }

依靠DBHelper和SQLiteDatabase 實現對業務的操作:

package com.wirelessqa.sqlite;import java.util.ArrayList;import java.util.List;import android.content.ContentValues;import android.content.Context;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import android.util.Log;/** *DBManager是建立在DBHelper之上,封裝了常用的業務方法 * @author bixiaopeng 2013-2-16 下午3:06:26 */public class DBManager {    private DBHelper       helper;    private SQLiteDatabase db;    public DBManager(Context context){        helper = new DBHelper(context);        //從helper中擷取database操作類 helper已經把資料庫封裝好了        db = helper.getWritableDatabase();    }    /**     * 向表info中增加多個成員資訊     *      * @param memberInfo     */    public void add(List<MemberInfo> memberInfo) {        db.beginTransaction();// 開始事務        try {            for (MemberInfo info : memberInfo) {                Log.i(WirelessQA.TAG, "------add memberInfo----------");                Log.i(WirelessQA.TAG, info.name + "/" + info.age + "/" + info.website + "/" + info.weibo);                // 向表info中插入資料                db.execSQL("INSERT INTO info VALUES(null,?,?,?,?)", new Object[] { info.name, info.age, info.website,                        info.weibo });            }            db.setTransactionSuccessful();// 事務成功        } finally {            db.endTransaction();// 結束事務        }    }    /**向表info中增加一個成員資訊     * @param _id     * @param name     * @param age     * @param website     * @param weibo     */    public void add(int _id, String name, int age, String website, String weibo) {        Log.i(WirelessQA.TAG, "------add data----------");        ContentValues cv = new ContentValues();        // cv.put("_id", _id);        cv.put("name", name);        cv.put("age", age);        cv.put("website", website);        cv.put("weibo", weibo);        db.insert(DBHelper.DB_TABLE_NAME, null, cv);        Log.i(WirelessQA.TAG, name + "/" + age + "/" + website + "/" + weibo);    }    /**     * 通過name來刪除資料     *      * @param name     */    public void delData(String name) {        // ExecSQL("DELETE FROM info WHERE name ="+"‘"+name+"‘");        String[] args = { name };        db.delete(DBHelper.DB_TABLE_NAME, "name=?", args);        Log.i(WirelessQA.TAG, "delete data by " + name);    }    /**     * 清空資料     */    public void clearData() {        ExecSQL("DELETE FROM info");        Log.i(WirelessQA.TAG, "clear data");    }    /**     * 通過名字查詢資訊,返回所有的資料     *      * @param name     */    public ArrayList<MemberInfo> searchData(final String name) {        String sql = "SELECT * FROM info WHERE name =" + "‘" + name + "‘";        return ExecSQLForMemberInfo(sql);    }    public ArrayList<MemberInfo> searchAllData() {        String sql = "SELECT * FROM info";        return ExecSQLForMemberInfo(sql);    }    /**     * 通過名字來修改值     *      * @param raw     * @param rawValue     * @param whereName     */    public void updateData(String raw, String rawValue, String whereName) {        String sql = "UPDATE info SET " + raw + " =" + " " + "‘" + rawValue + "‘" + " WHERE name =" + "‘" + whereName                     + "‘";        ExecSQL(sql);        Log.i(WirelessQA.TAG, sql);    }    /**     * 執行SQL命令返回list     *      * @param sql     * @return     */    private ArrayList<MemberInfo> ExecSQLForMemberInfo(String sql) {        ArrayList<MemberInfo> list = new ArrayList<MemberInfo>();        Cursor c = ExecSQLForCursor(sql);        while (c.moveToNext()) {            MemberInfo info = new MemberInfo();            info._id = c.getInt(c.getColumnIndex("_id"));            info.name = c.getString(c.getColumnIndex("name"));            info.age = c.getInt(c.getColumnIndex("age"));            info.website = c.getString(c.getColumnIndex("website"));            info.weibo = c.getString(c.getColumnIndex("weibo"));            list.add(info);        }        c.close();        return list;    }    /**     * 執行一個SQL語句 不返回任何資料     *      * @param sql     */    private void ExecSQL(String sql) {        try {            db.execSQL(sql);            Log.i("execSql: ", sql);        } catch (Exception e) {            Log.e("ExecSQL Exception", e.getMessage());            e.printStackTrace();        }    }    /**     * 執行SQL,返回一個遊標     *      * @param sql     * @return     */    private Cursor ExecSQLForCursor(String sql) {        Cursor c = db.rawQuery(sql, null);        return c;    }    public void closeDB() {        db.close();    }}
會員資訊的JavaBean – MemberInfo.java首頁顯示 – MainActivity.java 顯示結果頁 – DisplayActivity.java 源碼下載:http://download.csdn.net/detail/wirelessqa/5066148

【Android資料存放區】SQLite使用執行個體(附源碼)(轉載)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.