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 ...
随机推荐
- 【LeetCode】042 Trapping Rain Water
题目: Given n non-negative integers representing an elevation map where the width of each bar is 1, co ...
- SimpliciTI使用
SimpliciTI组网过程介绍 1.SimpliciTI支持点对点和星形的网络拓扑结构. 下面介绍以AP为中心的SimpliciTI网路协议的星形拓扑结构通信过程 1)当ED节点上电之后就扫描信 ...
- IOS技能要求
iOS专业技能: 拥有独立开发iOS APP应用的能力,并且独立开发过多款应用:熟练掌握iOS主流界面布局设计,基本控件和自定义控件的使用,事件处理及事件分发机制:熟练掌握工厂.代理.观察者.单例等多 ...
- Ajax的属性
1.属性列表 url: (默认: 当前页地址) 发送请求的地址. type: (默认: "GET") 请求方式 ("POST" 或 "GET ...
- 《精通Spring4.X企业应用开发实战》读后感第五章(注入参数详解)
- CodeForces 467D(267Div2-D)Fedor and Essay (排序+dfs)
D. Fedor and Essay time limit per test 2 seconds memory limit per test 256 megabytes input standard ...
- Java之匿名类讲解
参考https://blog.csdn.net/jiaotuwoaini/article/details/51542059 匿名类,正如名字一样在java中没有名字标识的类,当然了编译后还是会安排一个 ...
- Spring入门第十六课
接上一次讲课 先看代码: package logan.spring.study.annotation.repository; public interface UserRepository { voi ...
- JavaScript操作服务器控件之Gridview控件
1.JavaScript脚本如下: <script language="javascript" type="text/javascript"> ...
- MS SQL Server的COALESCE函数
MS SQL Server的COALESCE函数是从一系列表达式中返回第一个NOT NULL的值. 检查[B],[Q],[S],[T],[U]的值: 检查顺序[B]->[Q]->[S]-& ...