android sqlite数据库操作

来源:互联网 发布:小王子经典语录 知乎 编辑:程序博客网 时间:2024/04/30 08:43

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);";
}

原创粉丝点击