android sqlite資料庫操作

來源:互聯網
上載者:User

1.DataBaseHelper類,用於建立和更新資料庫表

package com.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper {

    public DataBaseHelper(Context context, String name, CursorFactory factory,
            int version) {
        super(context, name, null, version);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SqlStatement.CREATE_TABLE_TEST_ALLEN);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

        Log.d("======database update=======",
                "database updated from old version " + oldVersion
                        + " new version " + newVersion);

        db.execSQL("DROP TABLE IF EXISTS " + SqlStatement.TABLE_TEST_DB_ALLEN);
        onCreate(db);
    }
}

2。DatabaseProcesser,用於資料庫的增刪改查操作

package com.db;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.db.model.Allen;

public class DatabaseProcesser {
    private static final String DB_NAME = "allen_test_database.db";
    private static final int DB_VERSION = 2;
    private static DatabaseProcesser instance = null;
    private DataBaseHelper DBHelper = null;
    private SQLiteDatabase mDB = null;
    private static Context context;

    /**
     *
     * @param context
     */
    public DatabaseProcesser(Context context) {
        instance = this;
    }

    public static DatabaseProcesser getInstance() {
        if (instance == null) {
            new DatabaseProcesser(context);
        }
        return instance;
    }

    /**
     * open database
     *
     * @throws SQLException
     */
    private void openDatabase() throws SQLException {
        if (DBHelper == null) {
            DBHelper = new DataBaseHelper(context, DB_NAME, null, DB_VERSION);
        }

        mDB = DBHelper.getWritableDatabase();
    }

    /**
     * close database
     */
    private void closeDatabase() {
        if (mDB != null) {
            mDB.close();
        }
    }

    /**
     *
     * @param name
     * @param time
     * @return
     */
    public boolean insertTestData(String name, String time) {

        boolean ret = true;

        ContentValues cv = new ContentValues();
        cv.put(SqlStatement.COLUMN_NAME, name);
        cv.put(SqlStatement.COLUMN_TIME, time);

        try {
            openDatabase();
            mDB.insertOrThrow(SqlStatement.TABLE_TEST_DB_ALLEN, null, cv);
        } catch (Exception e) {
            ret = false;
            e.printStackTrace();
        } finally {
            closeDatabase();
        }

        return ret;
    }

    /**
     *
     * @param id
     * @return
     */
    public boolean deleteTestData(int id) {

        boolean ret = true;
        String sql = "delete * from table_allen where id = " + id;

        try {
            openDatabase();
            mDB.execSQL(sql);
        } catch (SQLException e) {
            ret = false;
            e.printStackTrace();
        } finally {
            closeDatabase();
        }

        return ret;
    }

    /**
     *
     * @param id
     * @param name
     * @param time
     * @return
     */
    public boolean updateTestData(int id, String name, String time) {
        return false;
    }

    /**
     *
     * @param id
     * @return
     */
    public Allen getTestData(int id) {
        return null;
    }

    /**
     *
     * @return
     */
    public List<Allen> getTestData() {
        List<Allen> allens = new ArrayList<Allen>();

        return allens;
    }
}

3.增刪改查方法:

    /**
     *
     * @param categoryName
     * @param categoryImageLevel
     * @return true when inserted, else return false
     */
    public boolean insertCategory(String categoryName, int categoryImageLevel) {
        boolean ret = true;
        Cursor cur = null;

        try {
            openDatabase();

            // category exist or not
            cur = mDb.rawQuery(SqlStatement.SQL_GET_CATEGORY_BY_NAME,
                    new String[] { categoryName });

            if (cur.moveToNext()) {
                // category exists in database
                ret = false;
            } else {
                // insert category
                ContentValues cv = new ContentValues();
                cv.put(SqlStatement.COLUMN_CATEGORY_NAME, categoryName);
                cv.put(SqlStatement.COLUMN_CATEGORY_IMAGE_LEVEL,
                        categoryImageLevel);

                mDb.insertOrThrow(SqlStatement.DB_TABLE_CATEGORY, null, cv);
            }

        } catch (SQLException e) {
            ret = false;
            e.printStackTrace();
        } finally {
            if (cur != null) {
                cur.close();
            }
            closeDatabase();
        }

        return ret;
    }

    /**
     *
     * @return a list of category
     */
    public List<CategoryInfo> getCategory() {
        List<CategoryInfo> ret = new ArrayList<CategoryInfo>();
        Cursor cur = null;

        try {
            openDatabase();
            cur = mDb.rawQuery(SqlStatement.SQL_GET_CATEGORY, null);

            while (cur.moveToNext()) {
                CategoryInfo category = new CategoryInfo();

                category.setId(cur.getInt(cur
                        .getColumnIndex(SqlStatement.COLUMN_ID)));
                category.setCategoryName(cur.getString(cur
                        .getColumnIndex(SqlStatement.COLUMN_CATEGORY_NAME)));
                category.setCategoryImageLevel(cur.getInt(cur
                        .getColumnIndex(SqlStatement.COLUMN_CATEGORY_IMAGE_LEVEL)));
                category.setCategoryClickCount(cur.getInt(cur
                        .getColumnIndex(SqlStatement.COLUMN_CATEGORY_CLICK_COUNT)));

                ret.add(category);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (cur != null) {
                cur.close();
            }
            closeDatabase();
        }

        return ret;
    }

    /**
     *
     * @param id
     * @return
     */
    public boolean deleteCategory(String categoryName) {

        boolean ret = true;

        try {
            openDatabase();
            mDb.execSQL("delete from " + SqlStatement.DB_TABLE_CATEGORY
                    + " where " + SqlStatement.COLUMN_CATEGORY_NAME + " = '"
                    + categoryName + "'");
        } catch (SQLException e) {
            ret = false;
            e.printStackTrace();
        } finally {
            closeDatabase();
        }

        return ret;
    }

4.SqlStatement,用於封裝SQL語句

package com.db;

public class SqlStatement {

    // table name
    public static final String TABLE_TEST_DB_ALLEN = "table_allen";

    // column name
    public static final String COLUMN_ID = "column_id";
    public static final String COLUMN_NAME = "column_name";
    public static final String COLUMN_TIME = "column_time";

    // sql statement to create table
    public static final String CREATE_TABLE_TEST_ALLEN = "create table if not exists "
            + TABLE_TEST_DB_ALLEN
            + " ("
            + COLUMN_ID
            + " integer primary key autoincrement, "
            + COLUMN_NAME
            + " varchar, "
            + COLUMN_TIME
            + " varchar);";
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.