码迷,mamicode.com
首页 > 数据库 > 详细

SQLite帮助类

时间:2016-05-13 03:56:06      阅读:224      评论:0      收藏:0      [点我收藏+]

标签:

1、首先写一个类继承自SQLiteOpenHelper

public class DBHelper extends SQLiteOpenHelper
{
    private static final int DATABASE_VERSION = 1;  //数据库版本号
    private static final String DATABASE_NAME = "";  //数据库名称

    public DBHelper(Context context)
    {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db)
    {
        String sql = "";
        db.execSQL(sql);
    }

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

    }
}

2、需要一个数据库管理类,比如插入、删除等

public abstract class DBDao
{
    private Context context;
    private DBHelper dbhelper;
    public SQLiteDatabase sqlitedatabase;

    public DBDao(Context context)
    {
        super();
        this.context = context;
    }

    /**
     * 打开数据库连接
     */
    public void openDB(Context context)
    {
        dbhelper = new DBHelper(context);
        sqlitedatabase = dbhelper.getWritableDatabase();
    }

    /**
     * 关闭数据库连接
     */
    public void closeDB(Context context)
    {
        if (sqlitedatabase.isOpen())
        {
            sqlitedatabase.close();
        }
    }

    /**
     * 更新数据
     */
    public int updata(String table_name, ContentValues values, int id)
    {
        openDB(context);
        int update = sqlitedatabase.update(table_name, values, "_id=?", new String[]{String.valueOf(id)});
        closeDB(context);
        return update;
    }

    /**
     * 插入数据
     */
    public void insert(String table_name, ContentValues values)
    {
        openDB(context);
        sqlitedatabase.insert(table_name, null, values);
        closeDB(context);
    }

    /**
     * 根据唯一标示_id删除数据
     */
    public void delete(String table_name, int id)
    {
        openDB(context);
        try
        {
            sqlitedatabase.delete(table_name, "_id=?", new String[]{String.valueOf(id)});
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            closeDB(context);
        }
    }

    /**
     * 查询数据
     */
    public void search(String table_name, int id)
    {
        SQLiteDatabase database = dbhelper.getReadableDatabase();

        String sql = "select * from " + table_name + " where _id = ?";
        Cursor cursor = database.rawQuery(sql, new String[]{String.valueOf(id)});
    }
}

SQLite帮助类

标签:

原文地址:http://blog.csdn.net/zhuzhiqiang_zhu/article/details/51337677

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!