SQLiteOpenHelper 的介绍
SQLiteOpenHelper是管理数据库,可以创建数据库,和管理数据库的版本,在继承SQLiteOpenHelper的类(extends SQLiteOpenHelper)里面,通过复写onCreate(SQLiteDatabase),onUpgrade(SQLiteDatabase, int, int) 和onOpen(SQLiteDatabase)(可选)来操作数据库。
1. onCreate()
public DBHelper (Context context, String name, CursorFactory factory,
int version) {
super(context, name, factory, version);
// TODO Auto-generated constructor stub
}
以上是SQLiteOpenHelper 的构造函数,当数据库不存在时,就会创建数据库,然后打开数据库(过程已经被封装起来了),再调用onCreate (SQLiteDatabase db)方法来执行创建表之类的操作。当数据库存在时,SQLiteOpenHelper 就不会调用onCreate (SQLiteDatabase db)方法了,它会检测版本号,若传入的版本号高于当前的,就会执行onUpgrade()方法来更新数据库和版本号。
2. onUpgrade()
更新数据库,包括删除表,添加表等各种操作。若版本是第一版,也就是刚刚建立数据库,onUpgrade()方法里面就不用写东西,因为第一版数据库何来更新之说,以后发布的版本,数据库更新的话,可以在onUpgrade()方法添加各种更新的操作。
3. 注意事项
创建完SQLiteOpenHelper 类之后,在主activity里面就可以通过SQLiteOpenHelper.getWritableDatabase()或者getReadableDatabase()方法来获取在SQLiteOpenHelper 类里面创建的数据库实例。(也就是说只有调用这两种方法才真正地实例化数据库)
getWritableDatabase() 方法————以读写方式打开数据库,如果数据库所在磁盘空间满了,而使用的又是getWritableDatabase() 方法就会出错。因为此时数据库就只能读而不能写
getReadableDatabase()方法————则是先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,但是当打开失败后会继续尝试以只读方法打开数据库。而不会报错。
SQLiteDatabase的介绍
Android提供了一个名为SQLiteDatabase的类,该类封装了一些操作数据库的API,使用该类可以完成对数据进行添加(Create)、查询(Retrieve)、更新(Update)和删除(Delete)操作(这些操作简称为CRUD)对SQLiteDatabase的学习,我们应该重点掌握execSQL()和rawQuery()方法。 execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句; rawQuery()方法用于执行select语句。
1. execSQL:
SQLiteDatabase db = ….;
db.execSQL(“insert into person(name, age) values(?,?)”, new Object[]{“测试数据”, 4});
db.close();
execSQL(String sql, Object[] bindArgs)方法的第一个参数为SQL语句,第二个参数为SQL语句中占位符参数的值,参数值在数组中的顺序要和占位符的位置对应
2. rawQuery:
rawQuery()方法的第一个参数为select语句;第二个参数为select语句中占位符参数的值,如果select语句没有使用占位符,该参数可以设置为null。带占位符参数的select语句使用例子如下:
Cursor cursor = db.rawQuery(“select * from person where name like ? and age=?”, new String[]{“%传智%”, “4”});
Cursor是结果集游标,用于对结果集进行随机访问,如果大家熟悉jdbc, 其实Cursor与JDBC中的ResultSet作用很相似。使用moveToNext()方法可以将游标从当前行移动到下一行,如果已经移过了结果集的最后一行,返回结果为false,否则为true。另外Cursor 还有常用的moveToPrevious()方法(用于将游标从当前行移动到上一行,如果已经移过了结果集的第一行,返回值为false,否则为true )、moveToFirst()方法(用于将游标移动到结果集的第一行,如果结果集为空,返回值为false,否则为true )和moveToLast()方法(用于将游标移动到结果集的最后一行,如果结果集为空,返回值为false,否则为true ) 。
3. 其他方法
除了前面给大家介绍的execSQL()和rawQuery()方法, SQLiteDatabase还专门提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query() 。这些方法实际上是给那些不太了解SQL语法使用的,对于熟悉SQL语法的程序员而言,直接使用execSQL()和rawQuery()方法执行SQL语句就能完成数据的添加、删除、更新、查询操作。
Insert()方法用于添加数据,各个字段的数据使用ContentValues进行存放。 ContentValues类似于MAP,相对于MAP,它提供了存取数据对应的put(String key, Xxx value)和getAsXxx(String key)方法, key为字段名称,value为字段值,Xxx指的是各种常用的数据类型,如:String、Integer等。
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(“name”, “测试数据”);
values.put(“age”, 4);
long rowid = db.insert(“person”, null, values);//返回新添记录的行号,与主键id无关
不管第三个参数是否包含数据,执行Insert()方法必然会添加一条记录,如果第三个参数为空,会添加一条除主键之外其他字段值为Null的记录。Insert()方法内部实际上通过构造insert SQL语句完成数据的添加,Insert()方法的第二个参数用于指定空值字段的名称,相信大家对该参数会感到疑惑,该参数的作用是什么?是这样的:如果第三个参数values 为Null或者元素个数为0, 由于Insert()方法要求必须添加一条除了主键之外其它字段为Null值的记录,为了满足SQL语法的需要, insert语句必须给定一个字段名,如:insert into person(name) values(NULL),倘若不给定字段名 , insert语句就成了这样: insert into person() values(),显然这不满足标准SQL的语法。对于字段名,建议使用主键之外的字段,如果使用了INTEGER类型的主键字段,执行类似insert into person(personid) values(NULL)的insert语句后,该主键字段值也不会为NULL。如果第三个参数values 不为Null并且元素的个数大于0 ,可以把第二个参数设置为null。 下面实例中都有使用,我就不一一举例了:
MainActivity.class
package com.example.db2;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
/**
* 主界面
*
* @author
*/
public class MainActivity extends Activity implements View.OnClickListener {
private Context context;
private DBManager dbManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
}
@Override
protected void onDestroy() {
super.onDestroy();
DBHelper.closeDB();
}
@Override
public void onClick(View v) {
int viewId = v.getId();
switch (viewId) {
case R.id.button_add_activity_main:
dbManager.add(new Person("A", "20"));
Toast.makeText(context, "增加一条数据", Toast.LENGTH_SHORT).show();
break;
case R.id.button_delete_activity_main:
dbManager.delete(1);
Toast.makeText(context, "删除一条数据", Toast.LENGTH_SHORT).show();
break;
case R.id.button_update_activity_main:
dbManager.update(5, new Person("B", "20"));
Toast.makeText(context, "更新一条数据", Toast.LENGTH_SHORT).show();
break;
case R.id.button_query_activity_main:
for (Person person : dbManager.query()) {
Log.e("yuzhentao", "name=" + person.name + ",age=" + person.age+",id="+person._id);
}
Toast.makeText(context, "查询一条数据", Toast.LENGTH_SHORT).show();
break;
case R.id.button_clear_activity_main:
dbManager.clear();
Toast.makeText(context, "清空数据", Toast.LENGTH_SHORT).show();
break;
}
}
private void initView() {
context = this;
findViewById(R.id.button_add_activity_main).setOnClickListener(this);
findViewById(R.id.button_delete_activity_main).setOnClickListener(this);
findViewById(R.id.button_update_activity_main).setOnClickListener(this);
findViewById(R.id.button_query_activity_main).setOnClickListener(this);
findViewById(R.id.button_clear_activity_main).setOnClickListener(this);
dbManager = DBManager.getInstance(getApplicationContext());
}
}
DBManager.class
package com.example.db2;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
/**
* 数据库管理器
*
* @author
*/
public class DBManager {
private SQLiteDatabase db;
private static DBManager DBManager;
public DBManager(Context context) {
db = DBHelper.getOpenedDB(context);
}
public static DBManager getInstance(Context context) {
if (DBManager == null) {
DBManager = new DBManager(context.getApplicationContext());
}
return DBManager;
}
/**
* 添加数据
*
* @param person:Person
*/
public void add(Person person) {
db.beginTransaction();
try {
db.execSQL("insert into " + Constants.TABLE_NAME_PERSON + " values (null, ?, ?)",
new Object[]{person.name, person.age});
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
/**
* 根据ID删除数据
*
* @param id:时间
*/
public void delete(int id) {
db.delete(Constants.TABLE_NAME_PERSON, "_id = ?", new String[]{String.valueOf(id)});
}
/**
* 清空数据
*/
public void clear() {
db.delete(Constants.TABLE_NAME_PERSON, "", new String[]{});
}
/**
* 根据ID更新数据
*
* @param _id:ID
* @param person:Person
*/
public void update(int _id, Person person) {
ContentValues cv = new ContentValues();
cv.put("name", person.name);
cv.put("age", person.age);
db.update(Constants.TABLE_NAME_PERSON, cv, "_id = ?", new String[]{String.valueOf(_id)});
}
/**
* 根据ID更新某个字段
*
* @param _id:ID
* @param key:键
* @param value:值
*/
public void update(int _id, String key, String value) {
ContentValues cv = new ContentValues();
cv.put(key, value);
db.update(Constants.TABLE_NAME_PERSON, cv, "_id = ?", new String[]{String.valueOf(_id)});
}
public void update(String name, Person person) {
ContentValues cv = new ContentValues();
cv.put("name", person.name);
cv.put("age", person.age);
db.update(Constants.TABLE_NAME_PERSON, cv, "name = ?", new String[]{name});
}
public void update(String name,String age, Person person) {
ContentValues cv = new ContentValues();
cv.put("name", person.name);
cv.put("age", person.age);
db.update(Constants.TABLE_NAME_PERSON, cv, "name=? and age=?", new String[]{name,age});
}
/**
* /**
* 查询数据
*
* @return ArrayList<Person>
*/
public ArrayList<Person> query() {
ArrayList<Person> personList = new ArrayList<>();
Cursor c = queryCursor(Constants.TABLE_NAME_PERSON);
while (c.moveToNext()) {
Person person = new Person();
person._id = c.getInt(c.getColumnIndex("_id"));
person.name = c.getString(c.getColumnIndex("name"));
person.age = c.getString(c.getColumnIndex("age"));
personList.add(person);
}
c.close();
return personList;
}
/**
* 查询指针
*
* @param tableName:表名
* @return Cursor
*/
public Cursor queryCursor(String tableName) {
return db.rawQuery("select * from " + tableName, null);
}
}
DBHelper.class
package com.example.db2;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* 数据库帮助器
*
* @author
*/
public class DBHelper extends SQLiteOpenHelper {
private static SQLiteDatabase db = null;
private static final String DATABASE_NAME = "person.db";
private static final int DATABASE_VERSION = 1;
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table if not exists " + Constants.TABLE_NAME_PERSON + " (_id integer primary key autoincrement, name text, age text)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("alter table person add column other string");
}
/**
* 获取打开的本地数据库
*
* @param context:Context
* @return SQLiteDatabase
*/
public static synchronized SQLiteDatabase getOpenedDB(Context context) {
if (db == null) {
DBHelper dbHelper = new DBHelper(context.getApplicationContext());
db = dbHelper.getWritableDatabase();
}
return db;
}
/**
* 关闭本地数据库
*/
public static void closeDB() {
if (db != null) {
db.close();
db = null;
}
}
}
Person.class
package com.example.db2;
/**
* 人
*
* @author
*/
public class Person {
public int _id;
public String name;
public String age;
public Person() {
}
public Person(String name, String age) {
this.name = name;
this.age = age;
}
}
Constants.class
package com.example.db2;
/**
* 常量
*
* @author yuzhentao
*/
public class Constants {
public static final String TABLE_NAME_PERSON = "person";
}
xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical">
<Button
android:id="@+id/button_add_activity_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:text="增"
android:textSize="16dp" />
<Button
android:id="@+id/button_delete_activity_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="@android:color/white"
android:text="删"
android:textSize="16dp" />
<Button
android:id="@+id/button_update_activity_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="@android:color/white"
android:text="改"
android:textSize="16dp" />
<Button
android:id="@+id/button_query_activity_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="@android:color/white"
android:text="查"
android:textSize="16dp" />
<Button
android:id="@+id/button_clear_activity_main"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:background="@android:color/white"
android:text="清空"
android:textSize="16dp" />
</LinearLayout>