精华内容
下载资源
问答
  • Android sqlite工具类
    千次阅读
    2015-11-04 11:47:38

    创建sqlite数据库

    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    
    
    public class DatabaseHelper extends SQLiteOpenHelper {
    
        //数据库名字
        private static final String DB_NAME = "note.db";
    
        //本版号
        private static final int VERSION = 1;
    
        //创建表
        private static final  String CREATE_TABLE_NOTE = "CREATE TABLE note(_id integer primary key autoincrement,"+
                "title text, content text, createDate text, updateDate text)";
    
        //删除表
        private static final String DROP_TABLE_NOTE = "drop table if exists note";
    
    
        public DatabaseHelper(Context context) {
            super(context, DB_NAME, null, VERSION);
        }
    
        @Override
        public void onCreate(SQLiteDatabase db) {
            //SQLiteDatabase 用于操作数据库的工具类
            db.execSQL(CREATE_TABLE_NOTE);
        }
    
        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL(DROP_TABLE_NOTE);
            db.execSQL(CREATE_TABLE_NOTE);
        }
    }
    


    下面是采用原生的方式进行增删改查

    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    
    import com.recker.note.data.MetaData;
    import com.recker.note.data.Note;
    
    import java.util.ArrayList;
    
    
    public class DatabaseAdapter {
    
        private DatabaseHelper dbHelper;
    
        public DatabaseAdapter(Context context) {
            dbHelper = new DatabaseHelper(context);
        }
    
        /**
         * 添加数据
         *
         * @param note
         */
        public void create(Note note) {
            String sql = "insert into note(title, content, createDate, updateDate)values(?,?,?,?)";
            Object[] args = {note.getTitle(), note.getContent(), note.getCreateDate(), note.getUpdateDate()};
            SQLiteDatabase db = dbHelper.getWritableDatabase();
    
            db.execSQL(sql, args);
            db.close();
        }
    
        /**
         * 删除数据
         *
         * @param id
         */
        public void remove(int id) {
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            String sql = "delete from note where _id = ?";
            Object[] args = {id};
            db.execSQL(sql, args);
            db.close();
        }
    
        /**
         * 修改数据
         *
         * @param note
         */
        public void update(Note note) {
            SQLiteDatabase db = dbHelper.getWritableDatabase();
            String sql = "update note set title = ?, content = ?, updateDate = ? where _id = ?";
            Object[] args = {note.getTitle(), note.getContent(), note.getUpdateDate(), note.getId()};
            db.execSQL(sql, args);
            db.close();
        }
    
        /**
         * 按id查询
         *
         * @param id
         * @return
         */
        public Note findById(int id) {
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            String sql = "select * from note where _id = ?";
            Cursor cursor = db.rawQuery(sql, new String[]{String.valueOf(id)});
    
            Note note = null;
            if (cursor.moveToNext()) {
                note = new Note();
    
                note.setId(cursor.getInt(cursor.getColumnIndexOrThrow(MetaData.NoteTable._ID)));
                note.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.TITLE)));
                note.setContent(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.CONTENT)));
                note.setCreateDate(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.CREATE_DATE)));
                note.setUpdateDate(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.UPDATE_DATE)));
            }
            cursor.close();
            db.close();
    
            return note;
        }
    
        /**
         * 查询所有
         *
         * @return
         */
        public ArrayList<Note> findAll() {
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            String sql = "select * from note";
            Cursor cursor = db.rawQuery(sql,null);
    
    
            ArrayList<Note> notes = new ArrayList<>();
            Note note = null;
            while (cursor.moveToNext()) {
                note = new Note();
    
                note.setId(cursor.getInt(cursor.getColumnIndexOrThrow(MetaData.NoteTable._ID)));
                note.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.TITLE)));
                note.setContent(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.CONTENT)));
                note.setCreateDate(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.CREATE_DATE)));
                note.setUpdateDate(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.UPDATE_DATE)));
                notes.add(note);
            }
            cursor.close();
            db.close();
            return notes;
        }
    
        /**
         * 分页查询
         *
         * @param limit 默认查询的数量
         * @param skip 跳过的行数
         * @return
         */
        public ArrayList<Note> findLimit(int limit, int skip) {
            SQLiteDatabase db = dbHelper.getReadableDatabase();
            String sql = "select * from note order by _id desc limit ? offset ?";
            String[] strs = new String[]{String.valueOf(limit), String.valueOf(skip)};
            Cursor cursor = db.rawQuery(sql,strs);
    
    
            ArrayList<Note> notes = new ArrayList<>();
            Note note = null;
            while (cursor.moveToNext()) {
                note = new Note();
    
                note.setId(cursor.getInt(cursor.getColumnIndexOrThrow(MetaData.NoteTable._ID)));
                note.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.TITLE)));
                note.setContent(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.CONTENT)));
                note.setCreateDate(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.CREATE_DATE)));
                note.setUpdateDate(cursor.getString(cursor.getColumnIndexOrThrow(MetaData.NoteTable.UPDATE_DATE)));
                notes.add(note);
            }
            cursor.close();
            db.close();
            return notes;
        }
    }
    



    更多相关内容
  • 轻量的 Android SQLite 数据库工具集合, 适合用SQLite做一些数据存储的项目. 根据Java实体自动生成数据库表. 不需要书写任何SQL语句即可实现对数据库的 创表 增 删 查 改 分页 操作. 所有的操作方法都是静态的...
  • Android SQLite学习工具

    2019-03-21 02:08:52
    NULL 博文链接:https://ghostfromheaven.iteye.com/blog/976680
  • sqlite数据库工具类

    2018-04-20 20:07:20
    基于room技术封装了数据库工具类,包含DbManager类和DbHelper类,方便复用
  • Android数据库可视化工具sqlitespy,绿色免安装版。可以直接查看数据库文件
  • Android Sqlite 工具类封装

    千次阅读 2018-11-01 10:30:58
    鉴于经常使用 Sqlite 数据库做数据持久化处理,进行了一点封装,方便使用。 该封装主要支持一下功能 支持多用户数据储存 支持 Sqlite数据库升级 支持传入 Sql 语句建表 支持 SQLiteDatabase 基本操作。比如...

    鉴于经常使用 Sqlite 数据库做数据持久化处理,进行了一点封装,方便使用。

    该封装类主要支持一下功能

    1. 支持多用户数据储存
    2. 支持 Sqlite数据库升级
    3. 支持传入 Sql 语句建表
    4. 支持 SQLiteDatabase 基本操作。比如:execSQL、rawQuery、insert等等
    5. 解决了数据库并发问题
        

    先贴上封装类代码

    /**
     *
     * @ClassName: DataBaseOpenHelper
     * @Description: 数据库工具类
     * @author lhy
     * @date 2014-10-9 下午2:36:41
     *
     */
    public class DataBaseOpenHelper extends SQLiteOpenHelper {
        private static Map<String, DataBaseOpenHelper> dbMaps = new HashMap<String, DataBaseOpenHelper>();
        private OnSqliteUpdateListener onSqliteUpdateListener;
        /**
         * 建表语句列表
         */
        private List<String> createTableList;
        private String nowDbName;
     
        private DataBaseOpenHelper(Context context, String dbName, int dbVersion, List<String> tableSqls) {
            super(context, dbName, null, dbVersion);
            nowDbName = dbName;
            createTableList = new ArrayList<String>();
            createTableList.addAll(tableSqls);
        }
     
        /**
         *
         * @Title: getInstance
         * @Description: 获取数据库实例
         * @param @param context
         * @param @param userId
         * @param @return
         * @return DataBaseOpenHelper
         * @author lihy
         */
        public static DataBaseOpenHelper getInstance(Context context, String dbName, int dbVersion, List<String> tableSqls) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(dbName);
            if (dataBaseOpenHelper == null) {
                dataBaseOpenHelper = new DataBaseOpenHelper(context, dbName, dbVersion, tableSqls);
            }
            dbMaps.put(dbName, dataBaseOpenHelper);
            return dataBaseOpenHelper;
        };
     
        @Override
        public void onCreate(SQLiteDatabase db) {
            for (String sqlString : createTableList) {
                db.execSQL(sqlString);
            }
        }
         
        /**
         *
         * @Title: execSQL
         * @Description: Sql写入
         * @param @param sql
         * @param @param bindArgs
         * @return void
         * @author lihy
         */
        public void execSQL(String sql, Object[] bindArgs) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            synchronized (dataBaseOpenHelper) {
                SQLiteDatabase database = dataBaseOpenHelper.getWritableDatabase();
                database.execSQL(sql, bindArgs);
            }
        }
     
        /**
         *
         * @Title: rawQuery
         * @Description:
         * @param @param sql查询
         * @param @param bindArgs
         * @param @return
         * @return Cursor
         * @author lihy
         */
        public Cursor rawQuery(String sql, String[] bindArgs) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            synchronized (dataBaseOpenHelper) {
                SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
                Cursor cursor = database.rawQuery(sql, bindArgs);
                return cursor;
            }
        }
     
        /**
         *
         * @Title: insert
         * @Description: 插入数据
         * @param @param table
         * @param @param contentValues 设定文件
         * @return void 返回类型
         * @author lihy
         * @throws
         */
        public void insert(String table, ContentValues contentValues) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            synchronized (dataBaseOpenHelper) {
                SQLiteDatabase database = dataBaseOpenHelper.getWritableDatabase();
                database.insert(table, null, contentValues);
            }
        }
     
        /**
         *
         * @Title: update
         * @Description: 更新
         * @param @param table
         * @param @param values
         * @param @param whereClause
         * @param @param whereArgs 设定文件
         * @return void 返回类型
         * @throws
         */
        public void update(String table, ContentValues values, String whereClause, String[] whereArgs) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            synchronized (dataBaseOpenHelper) {
                SQLiteDatabase database = dataBaseOpenHelper.getWritableDatabase();
                database.update(table, values, whereClause, whereArgs);
            }
        }
        /**
         *
         * @Title: delete
         * @Description:删除
         * @param @param table
         * @param @param whereClause
         * @param @param whereArgs
         * @return void
         * @author lihy
         */
        public void delete(String table, String whereClause, String[] whereArgs) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            synchronized (dataBaseOpenHelper) {
                SQLiteDatabase database = dataBaseOpenHelper.getWritableDatabase();
                database.delete(table, whereClause, whereArgs);
            }
        }
     
        /**
         *
         * @Title: query
         * @Description: 查
         * @param @param table
         * @param @param columns
         * @param @param selection
         * @param @param selectionArgs
         * @param @param groupBy
         * @param @param having
         * @param @param orderBy
         * @return void
         * @author lihy
         */
        public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having,
                String orderBy) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            synchronized (dataBaseOpenHelper) {
                SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
                // Cursor cursor = database.rawQuery("select * from "
                // + TableName.TABLE_NAME_USER + " where userId =" + userId, null);
                Cursor cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy);
                return cursor;
            }
        }
        /**
         *
         * @Description:查
         * @param table
         * @param columns
         * @param selection
         * @param selectionArgs
         * @param groupBy
         * @param having
         * @param orderBy
         * @param limit
         * @return
         * Cursor
         * @exception:
         * @author: lihy
         * @time:2015-4-3 上午9:37:29
         */
        public Cursor query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having,
                String orderBy,String limit) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            synchronized (dataBaseOpenHelper) {
                SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
                // Cursor cursor = database.rawQuery("select * from "
                // + TableName.TABLE_NAME_USER + " where userId =" + userId, null);
                Cursor cursor = database.query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit);
                return cursor;
            }
        }
     
        /**
         *
         * @Description 查询,方法重载,table表名,sqlString条件
         * @param @return
         * @return Cursor
         * @author lihy
         */
        public Cursor query(String tableName, String sqlString) {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            synchronized (dataBaseOpenHelper) {
                SQLiteDatabase database = dataBaseOpenHelper.getReadableDatabase();
                Cursor cursor = database.rawQuery("select * from " + tableName + " " + sqlString, null);
     
                return cursor;
            }
        }
     
        /**
         * @see android.database.sqlite.SQLiteOpenHelper#close()
         */
        public void clear() {
            DataBaseOpenHelper dataBaseOpenHelper = dbMaps.get(nowDbName);
            dataBaseOpenHelper.close();
            dbMaps.remove(dataBaseOpenHelper);
        }
     
        /**
         * onUpgrade()方法在数据库版本每次发生变化时都会把用户手机上的数据库表删除,然后再重新创建。<br/>
         * 一般在实际项目中是不能这样做的,正确的做法是在更新数据库表结构时,还要考虑用户存放于数据库中的数据不会丢失,从版本几更新到版本几。(非
         * Javadoc)
         *
         * @see android.database.sqlite.SQLiteOpenHelper#onUpgrade(android.database.sqlite
         *      .SQLiteDatabase, int, int)
         */
        @Override
        public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
            if (onSqliteUpdateListener != null) {
                onSqliteUpdateListener.onSqliteUpdateListener(db, arg1, arg2);
            }
        }
     
        public void setOnSqliteUpdateListener(OnSqliteUpdateListener onSqliteUpdateListener) {
            this.onSqliteUpdateListener = onSqliteUpdateListener;
        }
    }

     数据库更新接口代码

    public interface OnSqliteUpdateListener {
        public void onSqliteUpdateListener(SQLiteDatabase db, int oldVersion, int newVersion);
    }

     

    展开全文
  • AndroidSQLite封装

    2013-03-08 17:12:44
    利用Java反射机制实现Android数据库操作的封装,不用频繁对数据库进行操作,定义好一个实例后,只需新增一行代码就能实现根据类名映射出相关的数据表名,列名,和相关的增删改查工作。类似于J2EE中的 Hibernate...
  • SQLite数据库工具类

    2021-05-27 01:11:50
    概述该数据库工具类依赖了Room的相关包,使用很方便,现整理归档如下。使用时可以直接当做工具类使用。步骤引入依赖implementation 'android.arch.persistence:db:1.0.0'implementation 'android.arch.persistence:...

    概述

    该数据库工具类依赖了Room的相关包,使用很方便,现整理归档如下。使用时可以直接当做工具类使用。步骤

    引入依赖

    implementation 'android.arch.persistence:db:1.0.0'

    implementation 'android.arch.persistence:db-framework:1.0.0'

    创建SupportDbManager

    package com.example.a002034.myapplication.db;

    import android.arch.persistence.db.SupportSQLiteDatabase;

    import android.arch.persistence.db.SupportSQLiteOpenHelper;

    import android.support.annotation.NonNull;

    import java.util.concurrent.atomic.AtomicInteger;

    /**

    * DbManager.

    *

    * @author xuzhuyun

    */

    public class SupportDbManager {

    private SupportSQLiteOpenHelper mOpenHelper;

    private SupportSQLiteDatabase mDb;

    private AtomicInteger mOpenCounter;

    public SupportDbManager(@NonNull SupportSQLiteOpenHelper openHelper) {

    this.mOpenHelper = openHelper;

    this.mOpenCounter = new AtomicInteger();

    }

    public void destroy() {

    this.mOpenHelper.close();

    this.mOpenHelper = null;

    this.mDb = null;

    this.mOpenCounter.set(0);

    this.mOpenCounter = null;

    }

    public synchronized SupportSQLiteDatabase openDb() {

    if (this.mOpenCounter.incrementAndGet() == 1) {

    this.mDb = this.mOpenHelper.getWritableDatabase();

    }

    return this.mDb;

    }

    public synchronized void closeDb() {

    if (this.mOpenCounter.decrementAndGet() == 0) {

    this.mOpenHelper.close();

    }

    }

    }

    创建DbHelper

    package com.example.a002034.myapplication.db;

    /**

    * .

    *

    * @author

    */

    import android.arch.persistence.db.SupportSQLiteDatabase;

    import android.arch.persistence.db.SupportSQLiteOpenHelper;

    import android.arch.persistence.db.framework.FrameworkSQLiteOpenHelperFactory;

    import android.util.Log;

    import com.example.a002034.myapplication.Configs;

    import com.example.a002034.myapplication.RootApp;

    /**

    * SQLiteOpenHelper.

    *

    * @author xuzhuyun

    */

    public class DbHelper {

    private static final String TAG = "DbHelper";

    private SupportSQLiteOpenHelper mOpenHelper;

    public DbHelper() {

    SupportSQLiteOpenHelper.Configuration configuration = SupportSQLiteOpenHelper.Configuration.builder(RootApp.getInstance())

    .name(Configs.DB_NAME)

    .callback(new DbCallback(Configs.DB_VERSION))

    .build();

    SupportSQLiteOpenHelper.Factory factory = new FrameworkSQLiteOpenHelperFactory();

    mOpenHelper = factory.create(configuration);

    }

    public SupportSQLiteOpenHelper getOpenHelper() {

    return mOpenHelper;

    }

    class DbCallback extends SupportSQLiteOpenHelper.Callback {

    DbCallback(int version) {

    super(version);

    }

    @Override

    public void onCreate(SupportSQLiteDatabase db) {

    Log.i(TAG, "[db] 创建数据库");

    // db.execSQL(Cabinet.CREATE_TABLE);

    // db.execSQL(Cell.CREATE_TABLE);

    // db.execSQL(Parcel.CREATE_TABLE);

    }

    @Override

    public void onUpgrade(SupportSQLiteDatabase db, int oldVersion, int newVersion) {

    Log.i(TAG,

    "[db] 升级数据库,db = [" + db.getPath() + "], oldVersion = [" + oldVersion + "], currentVersion = [" + newVersion + "]");

    }

    }

    }

    以上RootApp是我们自定义的Application类,目的是获取Context对象,这里自己获取就好.我的RootApp代码是:

    package com.example.a002034.myapplication;

    import android.app.Application;

    /**

    * Application.

    *

    * @author xuzhuyun

    */

    public class RootApp extends Application {

    private static final String TAG = "RootApp";

    private static RootApp mContext;

    @Override

    public void onCreate() {

    super.onCreate();

    mContext = this;

    //初始化数据库

    Configs.getInstance().init();

    }

    public static RootApp getInstance() {

    if (mContext == null) {

    mContext = new RootApp();

    }

    return mContext;

    }

    }

    记得在Application类中初始化数据库。

    创建用到的配置类Configs

    package com.example.a002034.myapplication;

    import com.example.a002034.myapplication.db.DbHelper;

    import com.example.a002034.myapplication.db.SupportDbManager;

    /**

    * 全局配置类.

    *

    * @author xuzhuyun

    */

    public class Configs {

    /**

    * 数据库名称.

    */

    public static final String DB_NAME = "test.db";

    /**

    * 数据库版本号.

    */

    public static final int DB_VERSION = 1;

    private SupportDbManager mDbManager;

    private Configs() {

    }

    public void init() {

    initPersistent();

    }

    public SupportDbManager getDbManager() {

    if (mDbManager == null) {

    throw new IllegalStateException("must invoke method init() first");

    }

    return mDbManager;

    }

    private void initPersistent() {

    DbHelper smartDbHelper = new DbHelper();

    mDbManager = new SupportDbManager(smartDbHelper.getOpenHelper());

    }

    private static class SingletonHolder {

    private static final Configs INSTANCE = new Configs();

    }

    public static Configs getInstance() {

    return SingletonHolder.INSTANCE;

    }

    }

    调用

    获取SupportDbManager对象和SupportSQLiteDatabase对象

    SupportDbManager dbManager = Configs.getInstance().getDbManager();

    SupportSQLiteDatabase db = dbManager.openDb();

    拿到这些对象后,我们就可以做数据库增删改查操作了。其中,结合该工具类,我们还可以集成sqldelight插件,以后再补上sqldelight的用法。

    Demo下载

    展开全文
  • sqlite 数据库封装htmlDatabaseUtil.java(封装的)javapackagecom.jack.androidbase.tools;importandroid.content.ContentValues;importandroid.content.Context;importandroid.database.Cursor;importandroid....

    sqlite 数据库封装类html

    DatabaseUtil.java(封装的类)java

    packagecom.jack.androidbase.tools;importandroid.content.ContentValues;importandroid.content.Context;importandroid.database.Cursor;importandroid.database.SQLException;importandroid.database.sqlite.SQLiteDatabase;importandroid.database.sqlite.SQLiteOpenHelper;importandroid.util.Log;/*** sqlite 数据库操做类*/

    public classDatabaseUtil {private static final String TAG = "DatabaseUtil";/*** Database Name*/

    private static final String DATABASE_NAME = "student_data";/*** Database Version*/

    private static final int DATABASE_VERSION = 1;/*** Table Name*/

    private static final String DATABASE_TABLE = "tb_student";/*** Table columns*/

    public static final String KEY_NAME = "name";public static final String KEY_GRADE = "grade";public static final String KEY_ROWID = "_id";/*** Database creation sql statement*/

    private static final String CREATE_TABLE =

    "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "

    + KEY_NAME + " text not null, " + KEY_GRADE + " text not null);";/*** Context*/

    private finalContext mCtx;privateDatabaseHelper mDbHelper;privateSQLiteDatabase mDb;/*** Inner private class. Database Helper class for creating and updating database.*/

    private static class DatabaseHelper extendsSQLiteOpenHelper {

    DatabaseHelper(Context context) {super(context, DATABASE_NAME, null, DATABASE_VERSION);

    }/*** onCreate method is called for the 1st time when database doesn't exists.*/@Overridepublic voidonCreate(SQLiteDatabase db) {

    Log.i(TAG,"Creating DataBase: " +CREATE_TABLE);

    db.execSQL(CREATE_TABLE);

    }/*** onUpgrade method is called when database version changes.*/@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, intnewVersion) {

    Log.w(TAG,"Upgrading database from version " + oldVersion + " to "

    +newVersion);

    }

    }/*** Constructor - takes the context to allow the database to be

    * opened/created

    *

    *@paramctx the Context within which to work*/

    publicDatabaseUtil(Context ctx) {this.mCtx =ctx;

    }/*** This method is used for creating/opening connection

    *

    *@returninstance of DatabaseUtil

    *@throwsSQLException*/

    public DatabaseUtil open() throwsSQLException {

    mDbHelper= newDatabaseHelper(mCtx);

    mDb=mDbHelper.getWritableDatabase();return this;

    }/*** This method is used for closing the connection.*/

    public voidclose() {

    mDbHelper.close();

    }/*** This method is used to create/insert new record record.

    *

    *@paramname

    *@paramgrade

    *@returnlong*/

    public longinsert(String name, String grade) {

    ContentValues initialValues= newContentValues();

    initialValues.put(KEY_NAME, name);

    initialValues.put(KEY_GRADE, grade);return mDb.insert(DATABASE_TABLE, null, initialValues);

    }/*** This method will delete record.

    *

    *@paramrowId

    *@returnboolean*/

    public boolean delete(longrowId) {return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;

    }/*** This method will deleteAll record.

    *

    *@return

    */

    public booleandeleteAll() {return mDb.delete(DATABASE_TABLE, " 1 ", null) > 0;

    }/*** This method will return Cursor holding all the records.

    *

    *@returnCursor*/

    publicCursor fetchAll() {return mDb.query(DATABASE_TABLE, newString[]{KEY_ROWID, KEY_NAME,

    KEY_GRADE},null, null, null, null, null);

    }/*** This method will return Cursor holding the specific record.

    *

    *@paramid

    *@returnCursor

    *@throwsSQLException*/

    public Cursor fetch(long id) throwsSQLException {

    Cursor mCursor=mDb.query(true, DATABASE_TABLE, newString[]{KEY_ROWID,

    KEY_NAME, KEY_GRADE}, KEY_ROWID+ "=" + id, null,null, null, null, null);if (mCursor != null) {

    mCursor.moveToFirst();

    }returnmCursor;

    }/*** This method will update record.

    *

    *@paramid

    *@paramname

    *@paramstandard

    *@returnboolean*/

    public boolean update(intid, String name, String standard) {

    ContentValues args= newContentValues();

    args.put(KEY_NAME, name);

    args.put(KEY_GRADE, standard);return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;

    }

    }

    使用详解:android

    DatabaseUtil dbUtil = new DatabaseUtil(this);

    dbUtil.open();

    switch (v.getId()) {

    case R.id.other_btn_sqlite_list: //查询

    Cursor cursor = dbUtil.fetchAll();

    if (cursor != null) {

    while (cursor.moveToNext()) {

    Log.i("Student", "ID:" + cursor.getInt(0) + ",Student Name: " + cursor.getString(1) +

    ",Grade: " + cursor.getString(2));

    }

    }

    break;

    case R.id.other_btn_sqlite_add:

    dbUtil.insert("Prashant Thakkar", "100");

    Log.i("Student", "add over");

    break;

    case R.id.other_btn_sqlite_update:

    dbUtil.update(1, "aa", "bb");

    Log.i("Student", "update over");

    break;

    case R.id.other_btn_sqlite_del:

    dbUtil.delete(2);

    Log.i("Student", "delete over");

    break;

    case R.id.other_btn_sqlite_del_all:

    dbUtil.deleteAll();

    Log.i("Student", "delete all over");

    break;

    }

    dbUtil.close();sql

    参考网址:数据库

    https://www.cnblogs.com/sowhat4999/p/4439856.htmlide

    https://www.cnblogs.com/ProMonkey/p/5765616.html   (有添加单例模式)fetch

    本博客地址: wukong1688this

    转载请著名出处!谢谢~~spa

    展开全文
  • 本文实例为大家分享了Android数据库操作工具类的具体代码,供大家参考,具体内容如下 HistoryDAO public class HistoryDAO { private DBConnection dbc = null; private SQLiteDatabase db = null; private ...
  • packagecom.zhxjz.map.util;importjava.util.List;importorg.apache.commons.lang.math.NumberUtils;importandroid.content.Context;importandroid.database.Cursor;importandroid.database.sqlite.SQLiteData...
  • Sqlite使用工具类

    2016-09-02 19:55:11
    http://blog.csdn.net/qq_25412055/article/details/52414420
  • Android实用的SQLite数据库工具类

    千次阅读 2017-10-19 22:55:07
    一个实用的Sqlite工具类,调用的时候只需DBUtils.getInstance().creads(this);即可完成创建数据库 之后依次调用方面就好 DBUtils.java package com.example.bookadmin.sqlite; import android.content....
  • 一个简单的基于AndroidSqlite数据库的操作封装,它有如下的好处:便捷地创建表和增添表字段灵活的数据类型处理通过操作对象来insert或者update表记录支持多种查询方式,支持多表自定义的复杂查询,支持分页查询支持...
  • 一.SQLite的介绍 1.SQLite简介 SQLite是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入 式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,...
  • Android学习笔记之封装数据库工具类 2016年09月30日 01:12:43 IT_RealMan 阅读数:4727 版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27630169/article/details/52708143 ...
  • 手写简化适用于安卓开发中的SQLite数据库工具类,包含数据的增删改查,适用于各个需要本地数据库开发。
  • android SQLiteStudio v2.15

    2017-11-21 15:20:49
    SQLiteStudio v2.15 查看android SQLite数据库的小工具,免安装。
  • 开源的android sqlite数据操作工具类
  • android sqlite 存储位置

    千次阅读 2020-12-23 04:08:51
    Android 开发中使用 SQLite 数据库SQLite 是一款非常流行的嵌入式数据库,它支持SQL查询,并且只用很少的内存。Android在运行时集成了 SQLite,所以每个 Android 应用程序都可以使用 SQLite 数据库。对数熟悉 SQL 的...
  • android SQLite封装

    千次阅读 2018-05-03 17:28:30
    /** * ... * @Description: 数据库工具类 * */ public class DataBaseOpenHelper extends SQLiteOpenHelper { private static Map&lt;String, DataBaseOpenHelper&gt; dbMaps = new...
  • android轻量级数据库SQlite工具类

    千次阅读 2017-11-16 17:29:02
    package com.android.mtov.Util; import android.content.ContentValues; import android.content.Context; import android.database.Cursor;...import android.database.sqlite.SQLiteDatabase; import android.util
  • SQLiteToExcel 库整合了 Apache POI 和一些基本的数据库查询操作,使得 SQLite 和 Excel 之间相互转换更加便捷。
  • Android sqlite数据库

    千次阅读 2022-04-22 15:37:06
    功能实现 1.新建一个sqlite module ,在布局中加一个按键,命名为“添加数据”,在MianActivity.java文件中根据id添加监听事件(按需求添加按键和对应的监听事件...3.新建DBOpenHelper工具类,User1类,UserDao接口..
  • 数据库(Database)是按照数据结构来组织、存储和管理数据的仓库,其不再仅仅是存储和管理数据,而转变成用户所需要的各种数据管理的方式。...而SQLite数据库是一款系统安全软件,那么本文主要是介...
  • sqlite 的简介 对于sqlite 就是一种轻型的嵌入式的数据库,多用于手机,车机等,至于他的原理百度有很多大佬对他的详细介绍,我就不在这里累述了。...一般可以把他看作一个工具类,私有化构造函数,增加
  • 制作一个Android Sqlite远程运维小工具

    千次阅读 2021-11-23 02:06:27
    学更好的别人,做更好的自己。——《微卡智享》本文长度为3280字,预计阅读7分钟前言前面的文章中《实现Android本地Sqlite数据库网络传输到PC端》中制作的将本地Sqlite数据库...
  • Android开发 SQLite数据库

    千次阅读 2021-12-09 20:35:08
    Android系统封装了一个:SqliteOpenHelper(它是抽象)是主要用来使用的SQLite的。 但实际使用SQLite数据有更加方便与便捷的方法:Room三角色 创建数据库 Activity_main.java Activity_main.xml ...
  • Androidsqlite的封装,实现CRUD

    热门讨论 2012-01-19 11:14:02
    大家好,个人觉得用Sqlite数据库时,经常需要进行机械性的CRUD操作,故对其进行了一下封装,希望能起到抛砖引玉的作用。 目的:封装共有的CRUD 下面简单的说一下使用步骤,如果觉得多余,可以无视。 1. 实现自己...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 24,946
精华内容 9,978
关键字:

androidsqlite工具类