Android 下的 SQLite 操作封装 —— DatabaseUtil
看到别人写的代码不错,对自己目前的开发很有用,所以转载一下,希望也能帮助到其他人:
1.DatabaseUtil.java(封装的类)
package com.dbexample; import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log; public class DatabaseUtil{ private static final String TAG = "DatabaseUtil"; /**
* Database Name
*/
private static final String DATABASE_NAME = "student_database"; /**
* 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_STUDENT_TABLE =
"create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME +" text not null, " + KEY_GRADE + " text not null);"; /**
* Context
*/
private final Context mCtx; private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb; /**
* Inner private class. Database Helper class for creating and updating database.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* onCreate method is called for the 1st time when database doesn't exists.
*/
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "Creating DataBase: " + CREATE_STUDENT_TABLE);
db.execSQL(CREATE_STUDENT_TABLE);
}
/**
* onUpgrade method is called when database version changes.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion);
}
} /**
* Constructor - takes the context to allow the database to be
* opened/created
*
* @param ctx the Context within which to work
*/
public DatabaseUtil(Context ctx) {
this.mCtx = ctx;
}
/**
* This method is used for creating/opening connection
* @return instance of DatabaseUtil
* @throws SQLException
*/
public DatabaseUtil open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
/**
* This method is used for closing the connection.
*/
public void close() {
mDbHelper.close();
} /**
* This method is used to create/insert new record Student record.
* @param name
* @param grade
* @return long
*/
public long createStudent(String name, String grade) {
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_GRADE, grade);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
/**
* This method will delete Student record.
* @param rowId
* @return boolean
*/
public boolean deleteStudent(long rowId) {
return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0;
} /**
* This method will return Cursor holding all the Student records.
* @return Cursor
*/
public Cursor fetchAllStudents() {
return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME,
KEY_GRADE}, null, null, null, null, null);
} /**
* This method will return Cursor holding the specific Student record.
* @param id
* @return Cursor
* @throws SQLException
*/
public Cursor fetchStudent(long id) throws SQLException {
Cursor mCursor =
mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME, KEY_GRADE}, KEY_ROWID + "=" + id, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
} /**
* This method will update Student record.
* @param id
* @param name
* @param standard
* @return boolean
*/
public boolean updateStudent(int id, String name, String standard) {
ContentValues args = new ContentValues();
args.put(KEY_NAME, name);
args.put(KEY_GRADE, standard);
return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + id, null) > 0;
}
}
2.代码使用方法
//插入
DatabaseUtil dbUtil = new DatabaseUtil(this);
dbUtil.open();
dbUtil.createStudent("Prashant Thakkar", "10th");
dbUtil.close(); //查询
DatabaseUtil dbUtil = new DatabaseUtil(this);
dbUtil.open();
Cursor cursor = dbUtil.fetchAllStudents();
if(cursor != null){
while(cursor.moveToNext()){
Log.i("Student", "Student Name: " + cursor.getString(1) +
" Grade " + cursor.getString(2));
}
}
dbUtil.close();
Android 下的 SQLite 操作封装 —— DatabaseUtil的更多相关文章
- [Android新手区] SQLite 操作详解--SQL语法
该文章完全摘自转自:北大青鸟[Android新手区] SQLite 操作详解--SQL语法 :http://home.bdqn.cn/thread-49363-1-1.html SQLite库可以解 ...
- Android下的SQLite数据库的相关操作及AndroidTestCase测试
一:创建数据库 package com.itcode.mysqlite; import android.content.Context; import android.database.sqlite. ...
- Android下利用SQLite数据库实现增删改查
1: 首先介绍如何利用adb查看数据库 1: adb shell 2: cd /data/data/包名/databases 3: sqlite3 数据库 4 接下来就可以进行数据库的sql语法 ...
- android 本地数据库sqlite的封装
单机android sqlite数据库的实现,这个数据库可与程序一起生成在安装包中 一.下载sqlite3.exe文件 二.运行 cmd 转到sqlite3.exe 所在目录 运行 sqlite ...
- Android下用Sqlite数据库存储数据
第一步: 写个类 ,继承 SQLiteOpenHelper public class MyDatabaseOpenHelper extends SQLiteOpenHelper { } 第二步: ...
- 无废话Android之android下junit测试框架配置、保存文件到手机内存、android下文件访问的权限、保存文件到SD卡、获取SD卡大小、使用SharedPreferences进行数据存储、使用Pull解析器操作XML文件、android下操作sqlite数据库和事务(2)
1.android下junit测试框架配置 单元测试需要在手机中进行安装测试 (1).在清单文件中manifest节点下配置如下节点 <instrumentation android:name= ...
- android中的数据库操作(SQLite)
android中的数据库操作 android中的应用开发很难避免不去使用数据库,这次就和大家聊聊android中的数据库操作. 一.android内的数据库的基础知识介绍 1.用了什么数据库 an ...
- android下获取无线wif信号、ssid、MAC等操作类
一个android下获取无线wif信号.ssid.MAC等操作的类. WifiAdmin.java package com.afu; import java.util.List; import and ...
- 在Android下通过ExifInterface类操作图片的Exif信息
什么是Exif 先来了解什么是Exif.Exif是一种图像文件格式,它的数据存储于JPEG格式是完全相同的,实际上Exif格式就是JPEG格式头插入了 数码照片的信息,包括拍摄的光圈.快门.平衡白.I ...
随机推荐
- ACM学习历程——NOJ1113 Game I(贪心 || 线段树)
Description 尼克发明了这样一个游戏:在一个坐标轴上,有一些圆,这些圆的圆心都在x轴上,现在给定一个x轴上的点,保证该点没有在这些圆内(以及圆上),尼克可以以这个点为圆心做任意大小的圆,他想 ...
- bzoj 4503 两个串 快速傅里叶变换FFT
题目大意: 给定两个\((length \leq 10^5)\)的字符串,问第二个串在第一个串中出现了多少次.并且第二个串中含有单字符通配符. 题解: 首先我们从kmp的角度去考虑 这道题从字符串数据 ...
- 重学JAVA基础(二):Java反射
看一下百度的解释: JAVA反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息 ...
- XAML 编码规范 (思考)
1.尽量和Blend统一 2.兄弟元素之间需要空行 4.父子元素之间不需要空格 3.每行尽量单个属性 5.Grid的Row和Column定义不需要空行 6.Style里的Setter中不需要单行一个属 ...
- LMV实验
在CentOS6.8上创建过程如下: #对需要创建lvm的卷进行磁盘分区[root@www ~13:40:48]#fdisk /dev/sde Device contains neither a va ...
- POJ - 2955 Brackets括号匹配(区间dp)
Brackets We give the following inductive definition of a “regular brackets” sequence: the empty sequ ...
- app.config 配置的一种用法
app.config文件 <?xml version="1.0" encoding="utf-8" ?> <configuration> ...
- apply的使用技巧
1.什么是apply?他和call有什么区别? apply:方法能劫持另外一个对象的方法,继承另外一个对象的属性. Function.apply(obj,args)方法能接收两个参数 obj:这个对象 ...
- PHP AES/ECB 128加密
class Security { public static function encrypt($input, $key) { $key=md5($key.md5($key)); $size = mc ...
- AGC001 C - Shorten Diameter【枚举】
一开始没看到要保证最后是树--所以一定要从叶子开始删 枚举重心,如果k是偶数,那么按当前重心提起来deep大于k/2的全都要切掉,这样枚举重心然后取min即可 奇数的话就是枚举直径中间的边,然后从两边 ...