Android SQLite嵌入式数据库(一)
SQLite的CURD
Android提供了一个名为SQLiteDatabase的类,该类封装了一些操作数据库的API,使用该类可以完成对数据进行添加(Create)、查询(Retrieve)、更新(Update)和删除(Delete)操作(这些操作简称为CRUD)。对SQLiteDatabase的学习,我们应该重点掌握execSQL()和rawQuery()方法。 execSQL()方法可以执行insert、delete、update和CREATE TABLE之类有更改行为的SQL语句; rawQuery()方法可以执行select语句。SQLiteDatabase还专门提供了对应于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query() 。这些方法实际上是给那些不太了解SQL语法的菜鸟使用的,对于熟悉SQL语法的程序员而言,直接使用execSQL()和rawQuery()方法执行SQL语句就能完成数据的添加、删除、更新、查询操作。
SQLite的事务管理
使用SQLiteDatabase的beginTransaction()方法可以开启一个事务,程序执行到endTransaction() 方法时会检查事务的标志是否为成功,如果为成功则提交事务,否则回滚事务。当应用需要提交事务,必须在程序执行到endTransaction()方法之前使用setTransactionSuccessful() 方法设置事务的标志为成功,如果不调用setTransactionSuccessful() 方法,默认会回滚事务。
SQLite创建、更新数据表
如果应用使用到了SQLite数据库,在用户初次使用软件时,需要创建应用使用到的数据库表结构及添加一些初始化记录,另外在软件升级的时候,也需要对数据表结构进行更新。在Android系统,为我们提供了一个名为SQLiteOpenHelper的类,该类用于对数据库版本进行管理,该类是一个抽象类,必须继承它才能使用。为了实现对数据库版本进行管理,SQLiteOpenHelper类有两种重要的方法,分别是onCreate(SQLiteDatabase db)和onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
当调用SQLiteOpenHelper的getWritableDatabase()或者getReadableDatabase()方法获取用于操作数据库的SQLiteDatabase实例的时候,如果数据库不存在,Android系统会自动生成一个数据库,接着调用onCreate()方法,onCreate()方法在初次生成数据库时才会被调用,在onCreate()方法里可以生成数据库表结构及添加一些应用使用到的初始化数据。onUpgrade()方法在数据库的版本发生变化时会被调用,数据库的版本是由程序员控制的,假设数据库现在的版本是1,由于业务的需要,修改了数据库表的结构,这时候就需要升级软件,升级软件时希望更新用户手机里的数据库表结构,为了实现这一目的,可以把原来的数据库版本设置为2(或其他数值),并且在onUpgrade()方法里面实现表结构的更新。当软件的版本升级次数比较多,这时在onUpgrade()方法里面可以根据原版号和目标版本号进行判断,然后作出相应的表结构及数据更新。
getWritableDatabase()和getReadableDatabase()方法都可以获取一个用于操作数据库的SQLiteDatabase实例。但getWritableDatabase() 方法以读写方式打开数据库,一旦数据库的磁盘空间满了,数据库就只能读而不能写,倘若使用的是getWritableDatabase() 方法就会出错。getReadableDatabase()方法先以读写方式打开数据库,如果数据库的磁盘空间满了,就会打开失败,当打开失败后会继续尝试以只读方式打开数据库。
Android SQLite嵌入式数据库(二)
- Project name: AndroidSQLite
- BuildTarget:Android2.1
- Application name: SQLite嵌入式数据库
- Package name: com.changcheng.sqlite
- Create Activity: AndroidSQLite
- Min SDK Version:7
- //MyOpenHelper继承自SQLiteOpenHelper类。我们需要创建数据表,必须重写onCreate(更新时重写onUpgrade方法)方法,在这个方法中创建数据表。
-
- package eoe.sqlite;
-
- import android.content.Context;
- import android.database.sqlite.SQLiteDatabase;
- import android.database.sqlite.SQLiteOpenHelper;
-
- public class MyOpenHelper extends SQLiteOpenHelper {
- private static final String name = "contants"; // 数据库名称
- private static final int version = 1; // 数据库版本
- public MyOpenHelper(Context context) {
-
- /**
- * CursorFactory指定在执行查询时获得一个游标实例的工厂类。 设置为null,则使用系统默认的工厂类。
- */
-
- super(context, name, null, version);
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
-
- // 创建contacts表,SQL表达式时提供的字段类型和长度仅为提高代码的可读性。
- db.execSQL("CREATE TABLE IF NOT EXISTS contacts("
- + "_id integer primary key autoincrement,"
- + "name varchar(20)," + "phone varchar(50))");
- }
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
- // 仅演示用,所以先删除表然后再创建。
- db.execSQL("DROP TABLE IF EXISTS contacts");
- this.onCreate(db);
- }
- }
Android SQLite嵌入式数据库(三)
4.编写ContactsService类
ContactsService类主要实现对业务逻辑和数据库的操作。
java代码:
- package eoe.sqlite;
-
- import java.util.ArrayList;
- import java.util.List;
- import android.content.Context;
- import android.database.Cursor;
- import com.changcheng.sqlite.MyOpenHelper;
- import com.changcheng.sqlite.entity.Contact;
-
- public class ContactsService {
- private MyOpenHelper openHelper;
- public ContactsService(Context context) {
- this.openHelper = new MyOpenHelper(context);
- }
-
- /**
- * 保存
- *
- * @param contact
- */
-
- public void save(Contact contact) {
- String sql = "INSERT INTO contacts (name, phone) VALUES (?, ?)";
- Object[] bindArgs = { contact.getName(), contact.getPhone() };
- this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);
- }
-
- /**
- * 查找
- *
- * @param id
- * @return
- */
-
- public Contact find(Integer id) {
- String sql = "SELECT _id,name, phone FROM contacts WHERE _id=?";
- String[] selectionArgs = { id + "" };
- Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,
- selectionArgs);
- if (cursor.moveToFirst())
- return new Contact(cursor.getInt(0), cursor.getString(1), cursor.getString(2));
- return null;
- }
-
- /**
- * 更新
- *
- * @param contact
- */
-
- public void update(Contact contact) {
- String sql = "UPDATE contacts SET name=?, phone=? WHERE _id=?";
- Object[] bindArgs = { contact.getName(), contact.getPhone(),contact.get_id() };
- this.openHelper.getWritableDatabase().execSQL(sql, bindArgs);
- }
-
- /**
- * 删除
- *
- * @param id
- */
-
- public void delete(Integer id) {
- String sql = "DELETE FROM contacts WHERE _id=?";
- Object[] bindArgs = { id };
- this.openHelper.getReadableDatabase().execSQL(sql, bindArgs);
- }
-
- /**
- * 获取记录数量
- *
- * @return
- */
-
- public long getCount() {
-
- String sql = "SELECT count(*) FROM contacts";
- Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,null);
-
- cursor.moveToFirst();
- return cursor.getLong(0);
- }
-
- /**
- * 获取分页数据
- *
- * @param startIndex
- * @param maxCount
- * @return
- */
-
- public List getScrollData(long startIndex, long maxCount) {
- String sql = "SELECT _id,name,phone FROM contacts LIMIT ?,?";
- String[] selectionArgs = { String.valueOf(startIndex),
- String.valueOf(maxCount) };
- Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,selectionArgs);
-
- List contacts = new ArrayList();
-
- while (cursor.moveToNext()) {
- Contact contact = new Contact(cursor.getInt(0),
- cursor.getString(1), cursor.getString(2));
- contacts.add(contact);
- }
- return contacts;
- }
-
- /**
- * 获取分页数据,提供给SimpleCursorAdapter使用。
- *
- * @param startIndex
- * @param maxCount
- * @return
- */
-
- public Cursor getScrollDataCursor(long startIndex, long maxCount) {
- String sql = "SELECT _id,name,phone FROM contacts LIMIT ?,?";
- String[] selectionArgs = { String.valueOf(startIndex),
- String.valueOf(maxCount) };
- Cursor cursor = this.openHelper.getReadableDatabase().rawQuery(sql,
- selectionArgs);
- return cursor;
-
- }
-
- }
Android SQLite嵌入式数据库(四)
5.编写测试类
编写一个针对ContactsService的测试类,测试ContactsService类中的各个方法是否正确。
java代码:
- package eoe.sqlite.test;
-
- import java.util.List;
- import com.changcheng.sqlite.MyOpenHelper;
- import com.changcheng.sqlite.entity.Contact;
- import com.changcheng.sqlite.service.ContactsService;
- import android.database.Cursor;
- import android.test.AndroidTestCase;
- import android.util.Log;
-
- public class ContactsServiceTest extends AndroidTestCase {
- private static final String TAG = "ContactsServiceTest";
- // 测试创建表
- public void testCreateTable() throws Throwable {
- MyOpenHelper openHelper = new MyOpenHelper(this.getContext());
- openHelper.getWritableDatabase();
- }
-
- // 测试save
- public void testSave() throws Throwable {
- ContactsService contactsService = new ContactsService(this.getContext());
- Contact contact1 = new Contact(null, "tom", "13898679876");
- Contact contact2 = new Contact(null, "lili", "13041094909");
- Contact contact3 = new Contact(null, "jack", "13504258899");
- Contact contact4 = new Contact(null, "heary", "1335789789");
- contactsService.save(contact1);
- contactsService.save(contact2);
- contactsService.save(contact3);
- contactsService.save(contact4);
- }
-
- // 测试find
- public void testFind() throws Throwable {
- ContactsService contactsService = new ContactsService(this.getContext());
- Contact contact = contactsService.find(1);
- Log.i(TAG, contact.toString());
- }
-
- // 测试update
- public void testUpdate() throws Throwable {
- ContactsService contactsService = new ContactsService(this.getContext());
- Contact contact = contactsService.find(1);
- contact.setPhone("1399889955");
- contactsService.update(contact);
- }
-
- // 测试getCount
- public void testGetCount() throws Throwable {
- ContactsService contactsService = new ContactsService(this.getContext());
- Log.i(TAG, contactsService.getCount() + "");
- }
-
- // 测试getScrollData
- public void testGetScrollData() throws Throwable {
- ContactsService contactsService = new ContactsService(this.getContext());
- List contacts = contactsService.getScrollData(0, 3);
- Log.i(TAG, contacts.toString());
- }
-
- // 测试getScrollDataCursor
- public void testGetScrollDataCursor() throws Throwable {
- ContactsService contactsService = new ContactsService(this.getContext());
- Cursor cursor = contactsService.getScrollDataCursor(0, 3);
- while (cursor.moveToNext()) {
- Contact contact = new Contact(cursor.getInt(0),
- cursor.getString(1), cursor.getString(2));
- Log.i(TAG, contact.toString());
- }
- }
-
- }
-
Android SQLite嵌入式数据库(五)
java代码:
- public class AndroidSQLite extends Activity {
- /** Called when the activity is first created. */
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- // 获取分页数据
- ContactsService contactsService = new ContactsService(this);
- List contacts = contactsService.getScrollData(0, 3);
-
- // 获取ListView
- ListView lv = (ListView) this.findViewById(R.id.listView);
-
- // 生成List>数据
- List> data = new ArrayList>();
- for (Contact contact : contacts) {
- HashMap item = new HashMap();
- item.put("_id", contact.get_id());
- item.put("name", contact.getName());
- item.put("phone", contact.getPhone());
- data.add(item);
-
- }
-
- // 生成Adapter
- SimpleAdapter adapter = new SimpleAdapter(this, data,
- R.layout.contactitem, new String[] { "_id", "name", "phone" },
- new int[] { R.id.tv_id, R.id.tv_name, R.id.tv_phone });
-
- // 设置ListView适配器
- lv.setAdapter(adapter);
-
- // 为ListView添加事件
- lv.setOnItemClickListener(new OnItemClickListener() {
-
- @Override
- public void onItemClick(AdapterView parent, View view,int position, long id) {
- HashMap item = (HashMap) parent.getItemAtPosition((int) id);
- Toast.makeText(AndroidSQLite.this, item.get("name").toString(),1).show();
- }
- });
- }
-
- }
-
上面编写的分页显示数据比较麻烦,Android为我们提供了一个SimpleCursorAdapter类。使用它可以方便的显示分页数据。将AndroidSQLite类修改为:
java代码:
-
- package eoe.sqlite;
-
- import com.changcheng.sqlite.R;
- import com.changcheng.sqlite.service.ContactsService;
- import android.app.Activity;
- import android.database.Cursor;
- import android.os.Bundle;
- import android.widget.ListView;
- import android.widget.SimpleCursorAdapter;
-
- public class AndroidSQLite extends Activity {
- /** Called when the activity is first created. */
-
-
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
-
- // 获取分页数据
- ContactsService contactsService = new ContactsService(this);
- Cursor cursor = contactsService.getScrollDataCursor(0, 3);
-
- // 获取ListView
- ListView lv = (ListView) this.findViewById(R.id.listView);
-
- // 创建Adapter
- SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
- R.layout.contactitem, cursor, new String[] { "_id", "name","phone" }, new int[] { R.id.tv_id, R.id.tv_name,R.id.tv_phone });
-
- // 设置ListView适配器
- lv.setAdapter(adapter);
-
- // 为ListView添加事件
- lv.setOnItemClickListener(new OnItemClickListener() {
-
- @Override
- public void onItemClick(AdapterView parent, View view,int position, long id) {
-
- Cursor cursor = (Cursor) parent.getItemAtPosition((int) position);
- Toast.makeText(AndroidSQLite.this, cursor.getString(1), 1).show();
- }
- });
- }
-
- }
PS:以上资料为转载,非本人原创!