首页 > 系统 > Android > 正文

第六篇 Android中SQLite数据库的增删改查

2019-11-09 18:25:47
字体:
来源:转载
供稿:网友

要求: 创建一个SQLite数据库,对数据库中的数据进行执行下列操作:

创建person表在表中插入几条数据根据给定的主键值,删除表中的条目根据给定的主键值,更新表中的数据根据给定的主键值,查找表中的数据根据给定的参数,分页查找表中数据获取表中记录的总数执行事务

步骤: 此次采用测试的方法来做这个小示例。 1. 首先创建一个Android项目FdataBase 2. 在清单文件中写入下列内容: 在manifest标签中间写入下面内容:

<!-- 在清单文件中指定指令集,指定测试的目标项目 --> <instrumentation android:name="android.test.InstrumentationTestRunner" android:targetPackage="hhh.exercise.fdatabase" > </instrumentation>

application 里面写入:

<uses-library android:name="android.test.runner" /> <!-- <uses-library android:name="android.test.runner"/>定义使用的类库 -->

3.在src下新建hhh.exercise.domian包,在包中创建一个javaBean,主要是为了方便后面的操作

package hhh.exercise.domian;/** * @author HHH * */public class Person { public Integer _id; public String name; public String phone; public Integer account; public Integer get_id() { return _id; } public void set_id(Integer _id) { this._id = _id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Integer getAccount() { return account; } public void setAccount(Integer account) { this.account = account; } public Person(Integer _id, String name, String phone, Integer account) { super(); this._id = _id; this.name = name; this.phone = phone; this.account = account; } public Person(String name, String phone, Integer account) { super(); this.name = name; this.phone = phone; this.account = account; } @Override public String toString() { return "Person [_id=" + _id + ", name=" + name + ", phone=" + phone + ", account=" + account + "]"; }}

4.在hhh.exercise.fdatabase包中创建MyOpenHelper.java,该类是为了创建和升级数据库

package hhh.exercise.fdatabase;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteDatabase.CursorFactory;import android.database.sqlite.SQLiteOpenHelper;/** * @author HHH * */public class MyOpenHelper extends SQLiteOpenHelper { PRivate static String CREATETABLE_PERSON = "create table person( _id Integer primary key autoincrement,name char(20),phone char(20),account char(20))"; private static String UPDATE_PERSON = "alter table person add salary char(20)"; public MyOpenHelper(Context context, String name, CursorFactory factory, int version) { super(context, name, factory, version); } /* * 创建数据库 */ @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CREATETABLE_PERSON); } /** * 升级数据库(当版本升级是,调用此处代码) * */ @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(UPDATE_PERSON); }}

5.在src下创建hhh.exercise.service包,新建OperateDB.java,该类是具体的对数据库执行增删改查的操作:

package hhh.exercise.service;import java.util.ArrayList;import java.util.List;import android.content.ContentValues;import android.database.Cursor;import android.database.sqlite.SQLiteDatabase;import hhh.exercise.domian.Person;/** * @author HHH * */public class OperateDB { /** * 插入数据:方法一 * * @param db需要操作的数据库 * @param person需要插入的数据 */ public void insert_1(SQLiteDatabase db, Person person) { db.execSQL("insert into person(name,phone,account) values(?,?,?)", new Object[] { person.getName(), person.getPhone(), person.getAccount() }); } /** * 插入数据:方法二 * * @param db需要操作的数据库 * @param person需要插入的数据 */ public void insert_2(SQLiteDatabase db, Person person) { // 把要插入的数据封装成ContentValues对象 ContentValues values = new ContentValues(); values.put("name", person.getName()); values.put("phone", person.getPhone()); values.put("account", person.getAccount()); // 把数据插入到数据库中 db.insert("person", null, values); } /** * 删除数据:方法一 * * @param db需要操作的数据库 * @param _id传入的主键值,根据该主键值删除数据 */ public void delete_1(SQLiteDatabase db, int _id) { db.execSQL("delete from person where _id=?", new Object[] { _id }); } /** * 0000000000000000000 删除数据:方法二 * * @param db需要操作的数据库 * @param _id传入的主键值,根据该主键值删除数据 */ public void delete_2(SQLiteDatabase db, int _id) { db.delete("person", "_id=?", new String[] { _id + "" }); } /** * 更新数据:方法一 * * @param db需要操作的数据库 * @param person根据给定的Person对象中的_id,更新表中数据 */ public void update_1(SQLiteDatabase db, Person person) { db.execSQL("update person set name=?,phone=?,account=? where _id=?", new String[] { person.getName(), person.getPhone(), person.getAccount() + "", person.get_id() + "" }); } /** * 更新数据:方法二 * * @param db需要操作的数据库 * @param person根据给定的Person对象中的_id,更新表中数据 */ public void update_2(SQLiteDatabase db, Person person) { // 把更新的数据封装成ContentValues对象 ContentValues values = new ContentValues(); values.put("name", person.getName()); values.put("phone", person.getPhone()); values.put("account", person.getAccount()); db.update("person", values, "_id=?", new String[] { person.get_id() + "" }); } /** * 查找单条数据:方法一 * * @param db需要操作的数据库对象 * @param _id传入的主键值,根据该值查找数据库中的数据 * @return */ public Person find_1(SQLiteDatabase db, int _id) { Person person = null; // 查询数据库中的数据,Cursor用于返回查询的结果集,移动指标可以任意查找其中记录(随机访问)· Cursor cursor = db.rawQuery("select _id,name,phone,account from person where _id=? ", new String[] { _id + "" }); // 循环遍历Cursor,取出里面的数据 while (cursor.moveToNext()) { // 根据列名,获取该列在cursor中的索引,进而获取该列的值 String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); int account = cursor.getInt(cursor.getColumnIndex("account")); person = new Person(_id, name, phone, account); } cursor.close(); return person; } /** * 查找单条数据:方法二 * * @param db需要操作的数据库对象 * @param _id传入的主键值,根据该值查找数据库中的数据 * @return */ public Person find_2(SQLiteDatabase db, int _id) { Person person = null; // 查询数据库中的数据,Cursor用于返回查询的结果集,移动指标可以任意查找其中记录(随机访问)· Cursor cursor = db.query("person", new String[] { "name", "phone", "account" }, "_id=?", new String[] { _id + "" }, null, null, null); // 循环遍历Cursor,取出里面的数据 while (cursor.moveToNext()) { // 根据列名,获取该列在cursor中的索引,进而获取该列的值 String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); int account = cursor.getInt(cursor.getColumnIndex("account")); person = new Person(_id, name, phone, account); } cursor.close(); return person; } /** * 分页获取数据库中的数据(采用按照主键升序查找)方法一 * * @param db需要操作的数据库 * @param offset分页开始的其实位置 * @param maxResult最大查询的记录数 * @return */ public List<Person> getScrollData_1(SQLiteDatabase db, int offset, int maxResult) { List<Person> list = new ArrayList<Person>(); // 执行数据库查询操作 Cursor cursor = db.rawQuery("select * from person order by _id asc limit ?,?", new String[] { String.valueOf(offset), String.valueOf(maxResult) }); // 循环遍历Cursor,取出里面的数据 while (cursor.moveToNext()) { // 根据列名,获取该列在cursor中的索引,进而获取该列的值 int rowId = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); int account = cursor.getInt(cursor.getColumnIndex("account")); Person person = new Person(rowId, name, phone, account); list.add(person); } return list; } /** * 分页获取数据库中的数据(采用按照主键升序查找):方法二 * * @param db需要操作的数据库 * @param offset分页开始的其实位置 * @param maxResult最大查询的记录数 * @return */ public List<Person> getScrollData_2(SQLiteDatabase db, int offset, int maxResult) { List<Person> list = new ArrayList<Person>(); // 执行数据库查询操作 Cursor cursor = db.query("person", null, null, null, null, null, "_id asc", offset + "," + maxResult); // 循环遍历Cursor,取出里面的数据 while (cursor.moveToNext()) { // 根据列名,获取该列在cursor中的索引,进而获取该列的值 int rowId = cursor.getInt(cursor.getColumnIndex("_id")); String name = cursor.getString(cursor.getColumnIndex("name")); String phone = cursor.getString(cursor.getColumnIndex("phone")); int account = cursor.getInt(cursor.getColumnIndex("account")); Person person = new Person(rowId, name, phone, account); list.add(person); } return list; } /** * 获取该数据库表中的记录数量:方法一 * * @param db */ public long getCount_1(SQLiteDatabase db) { long count = 0; Cursor cursor = db.rawQuery("select count(*) from person ", null); if (cursor.moveToFirst()) { count = cursor.getLong(0); } return count; } /** * 获取该数据库表中的记录数量:方法二 * * @param db */ public long getCount_2(SQLiteDatabase db) { long count = 0; Cursor cursor = db.rawQuery("select count(*) from person ", null); if (cursor.moveToFirst()) { count = cursor.getLong(0); } return count; } /** * 处理事务 * * @param db要操作的数据库对下岗 * @param _id_1需要操作的对象1的主键 * @param _id_2需要操作的对象2的主键 * @param money需要转账的金额 */ public void transaction(SQLiteDatabase db, int _id_1, int _id_2, int money) { // 该事务模拟由对象1转账给对象2,转账的金额为money try { // 开启事务 db.beginTransaction(); // 通过主键查找数据库 Person person_1 = find_1(db, _id_1); Person person_2 = find_1(db, _id_2); // 判断Person对象是否存在,存在就进行转账操作 if (person_1 != null && person_2 != null) { int account_1 = person_1.getAccount()-money; int account_2 = person_2.getAccount()+money; person_1.setAccount(account_1); person_2.setAccount(account_2); // 更新数据库 update_1(db, person_1); update_1(db, person_2); // 设置成功标志 db.setTransactionSuccessful(); } } finally { // 结束事务。有两种情况,提交(commit)和回滚(rollback)。 // 事务提交或者回滚由事务的标志决定,事务标志位true就是提交,false就是回滚。默认情况下是false db.endTransaction(); } }}

6.新建一个测试类,用来测试OperateDB.java中的方法

package hhh.exercise.test;import java.util.List;import android.database.sqlite.SQLiteDatabase;import android.test.AndroidTestCase;import android.util.Log;import hhh.exercise.domian.Person;import hhh.exercise.fdatabase.MyOpenHelper;import hhh.exercise.service.OperateDB;/** * @author HHH * */@SuppressWarnings("deprecation")public class PersonTest extends AndroidTestCase { private static String TAG = "TEST"; private OperateDB operateDB; private SQLiteDatabase db; /** * 在测试框架初试化完毕之后,测试方法调用之前执行 */ @Override protected void setUp() throws Exception { // getContext()用于获取虚拟的上下文对象 MyOpenHelper openHelper = new MyOpenHelper(getContext(), "FdataBase.db", null, 1); // 获取数据库对象 db = openHelper.getWritableDatabase(); // 初始化OperateDB对象,方便调用该对象中的方法 operateDB = new OperateDB(); } /** * 测试方法执行完毕之后,执行该方法 */ @Override protected void tearDown() throws Exception { // 关闭数据库 db.close(); } /** * 测试插入数据的方法一 * * @throws Exception */ public void testInsert_1() throws Exception { // 为操作方便,一次性插入多条数据 for (int i = 1; i <= 21; ++i) { operateDB.insert_1(db, new Person("张三" + i, "3" + i, 300)); } } /** * 测试插入数据的方法二 * * @throws Exception */ public void testInsert_2() throws Exception { for (int i = 1; i <= 21; ++i) { operateDB.insert_2(db, new Person("李四" + i, "3" + i, 300)); } } /** * 测试删除数据的方法一 * * @throws Exception */ public void testDelete_1() throws Exception { operateDB.delete_1(db, 21); } /** * 测试删除数据的方法二 * * @throws Exception */ public void testDelete_2() throws Exception { operateDB.delete_2(db, 42); } /** * 测试更新数据的方法一 * * @throws Exception */ public void testUpdate_1() throws Exception { operateDB.update_1(db, new Person(1, "王五", "55", 500)); } /** * 测试更新数据的方法二 * * @throws Exception */ public void testUpdate_2() throws Exception { operateDB.update_1(db, new Person(2, "二狗", "22", 200)); } /** * 测试查找数据的方法一 * * @throws Exception */ public void testFind_1() throws Exception { Person person = operateDB.find_1(db, 1); Log.i(TAG, person.toString()); } /** * 测试查找数据的方法二 * * @throws Exception */ public void testFind_2() throws Exception { Person person = operateDB.find_2(db, 2); Log.i(TAG, person.toString()); } /** * 测试分页获取数据的方法一 * * @throws Exception */ public void testGetScrollData_1() throws Exception { List<Person> list = operateDB.getScrollData_1(db, 0, 40); for (Person person : list) { Log.i(TAG, person.toString()); } } /** * 测试分页获取数据的方法二 * * @throws Exception */ public void testGetScrollData_2() throws Exception { List<Person> list = operateDB.getScrollData_2(db, 0, 40); for (Person person : list) { Log.i(TAG, person.toString()); } } /** * 测试获取表中总的记录数的方法一 * * @throws Exception */ public void testGetCount_1() throws Exception { long count = operateDB.getCount_1(db); Log.i(TAG, count + ""); } /** * 测试获取表中总的记录数的方法二 * * @throws Exception */ public void testGetCount_2() throws Exception { long count = operateDB.getCount_2(db); Log.i(TAG, count + ""); } /** * 测试事务 * * @throws Exception */ public void testTransaction() throws Exception { operateDB.transaction(db, 3, 4, 33); }}

7.最后对PersonTest.java中的每个方法进行Android.Junit.test就可以了.


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表