Android学习笔记----SQLiteDatabase 自带添加、删除、更新、查询的操作方法:实现添加,删除,更新,查询,和分页,统计

来源:互联网 发布:java float double 编辑:程序博客网 时间:2024/04/30 04:02
7.除了前面给大家介绍的execSQL()和rawQuery()方法, SQLiteDatabase还专门提供了对应


于添加、删除、更新、查询的操作方法: insert()、delete()、update()和query() 。这些


方法实际上是给那些不太了解SQL语法的菜鸟使用的,对于熟悉SQL语法的程序员而言,直接


使用execSQL()和rawQuery()方法执行SQL语句就能完成数据的添加、删除、更新、查询操作



--------------------------------------------------------------
8.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", "credream");
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。
--------------------------------------------------------------
2.delete()方法的使用:
  SQLiteDatabase db = databaseHelper.getWritableDatabase();
  db.delete("person", "personid<?", new String[]{"2"});
  db.close();
  上面代码用于从person表中删除personid小于2的记录。
--------------------------------------------------------------------
3.update()方法的使用:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(“name”, “传智播客”);//key为字段名,value为值
db.update("person", values, "personid=?", new String[]{"1"}); 
db.close();
上面代码用于把person表中personid等于1的记录的name字段的值改为“credream”。
--------------------------------------------------------------------------
4.query()方法实际上是把select语句拆分成了若干个组成部分,然后作为方法的输入参数:
SQLiteDatabase db = databaseHelper.getWritableDatabase();
Cursor cursor = db.query("person", new String[]{"personid,name,age"}, "name like 


?", new String[]{"%传智%"}, null, null, "personid desc", "1,2");
while (cursor.moveToNext()) {
         int personid = cursor.getInt(0); //获取第一列的值,第一列的索引从0开始
        String name = cursor.getString(1);//获取第二列的值
        int age = cursor.getInt(2);//获取第三列的值
}
cursor.close();
db.close(); 
上面代码用于从person表中查找name字段含有“传智”的记录,匹配的记录按personid降序


排序,对排序后的结果略过第一条记录,只获取2条记录。
query(table, columns, selection, selectionArgs, groupBy, having, orderBy, limit)


方法各参数的含义:
table:表名。相当于select语句from关键字后面的部分。如果是多表联合查询,可以用逗号


将两个表名分开。
columns:要查询出来的列名。相当于select语句select关键字后面的部分。
selection:查询条件子句,相当于select语句where关键字后面的部分,在条件子句允许使


用占位符“?”
selectionArgs:对应于selection语句中占位符的值,值在数组中的位置与占位符在语句中


的位置必须一致,否则就会有异常。
groupBy:相当于select语句group by关键字后面的部分
having:相当于select语句having关键字后面的部分
orderBy:相当于select语句order by关键字后面的部分,如:personid desc, age asc;
limit:指定偏移量和获取的记录数,相当于select语句limit关键字后面的部分。
------------------------------------------------------------------------
1.利用sqlite提供的方法来实现添加,删除,更新,查询,和分页,统计
--------------------------------------------
/DBSQLIte/src/com/credream/service/OtherPersonService.java
package com.credream.service;


import java.util.ArrayList;
import java.util.List;


import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import com.credream.entity.Person;


public class OtherPersonService
{
private DBOpenHelter dbOpenHelter;
public OtherPersonService(Context context){
this.dbOpenHelter=new DBOpenHelter(context);
}
/**
* 添加记录
* @param person
*/
public void save (Person person){
SQLiteDatabase db=dbOpenHelter.getWritableDatabase();
//SQLiteDatabase db2=dbOpenHelter.getWritableDatabase();
//这里获得的数据库实例和db这个数据库实例是一样的,因为数据库有缓存


功能
//在源码里进行了判断,如果得到的数据库实例不为null,并且已经打开,并


且是只读的,那么
//就直接返回这个实例
        //dbOpenHelter.getWritableDatabase().execSQL(sql);这里和db.execSQL("作用


是一样的
//db.execSQL("insert into person (name,phone) values


('"+person.getName()+"','"+person.getPhone()+"')");
   //上面这种写法是错误的,因为当用户输入cre'dream的时候那么sql语句就成了
//insert into person (name,phone) values


('cre'dream','15066659146')这样会出现sql语法错误
//所以,应该用转义字符
ContentValues values=new ContentValues();
values.put("name", person.getName());
values.put("phone", person.getPhone());
db.insert("person", null, values);
//这里第二个字段,是空值字段,如果用户传过去的字段是空集合那么就无


法组拼接sql
//比如:db.insert("person", "name",null );这时候,就是代表name可以


为null
//insert into person(name) values(NULL);
//所以当第三个参数不是null,的时候第二个参数是没用的直接设置为


null就可以了
//db.insert("person", "personid",null );对应的sql:insert into 


person(personid) values(NULL);
//这时候主键为null,按理说是不正确的,但是sqlite做了处理,这个时候其


实取了主键自增值作为personid的值
 
//在源代码里,也是通过构造sql语句来完成,数据的添加的
//db.execSQL("insert into person (name,phone) values(?,?)",new 


Object[]{person.getName(),person.getPhone()});
//db.close();//数据库也可以不关闭,因为这样的话可以提升性能,因为不用频繁的


开关数据库

}
/**
* 删除记录
* @param person
*/
public void delete (Integer id){
SQLiteDatabase db=dbOpenHelter.getWritableDatabase();
db.delete("person", "personid=?", new String[]{id.toString()});
//这里拼接的时候自动的给加了where不要重复加
//db.execSQL("delete from person  where personid=?",new Object[]


{id});
}
/**
* 更新记录
* @param person
*/
public void update(Person person){
SQLiteDatabase db=dbOpenHelter.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("name", person.getName());
values.put("phone", person.getPhone());
db.update("person", values,"personid=?",new String[]


{person.getId().toString()} );
//db.execSQL("update  person set name=?,phone=?   where 


personid=?",new Object[]{person.getName(),person.getPhone(),person.getId()});

}
/**
* 查找记录
* @param id
* @return
*/
public Person find (Integer id){
SQLiteDatabase db=dbOpenHelter.getReadableDatabase();
//getReadableDatabase();这个方法里面调用了getWritableDatabase();


方法,来取得数据库操作实例,只有调用
//失败的时候就会发现异常,当数据磁盘满了,会抛出异常,这时候会打开这


个实例的数据库
//然后开始读取,这样当磁盘满的时候,
//当数据库磁盘空间没有满的时候,返回的数据库操作实例是一样的:可读


可写,当数据库磁盘满了,返回的数据库
//操作实例是只读的
//Cursor cursor=db.query("person", new String[]{"personid","name","phone"}, 


"personid=?", new String[]{id.toString()}, null, null, null);
Cursor cursor=db.query("person", null, "personid=?", new String


[]{id.toString()}, null, null, null);
//Passing null will return all columns,第二个参数传入null,将会获


取所有的列
//Cursor cursor=db.rawQuery("select * from person  where personid=?",new String


[]{id.toString()});
//游标存放结果
if(cursor.moveToFirst()){
int personid=cursor.getInt(cursor.getColumnIndex("personid"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String phone=cursor.getString(cursor.getColumnIndex("phone"));
return new Person(personid,name,phone);

}//当有数据会返回true,否则为false
cursor.close();
return null;
}

//处理分页
/**
* 分页获取记录
* offset:跳过前面几条记录
* maxlength:获取几条
*/
public List<Person> getScrollData(int offset,int MaxResult){
List<Person> persons=new ArrayList<Person>();
SQLiteDatabase db=dbOpenHelter.getReadableDatabase();
Cursor cursor=db.query("person", null, null, null, null,null, 


"personid asc", offset+","+MaxResult);

//Cursor cursor=db.rawQuery("select * from person order by 


personid asc limit ?,?",
//new String[]{String.valueOf(offset),String.valueOf


(MaxResult)});
while(cursor.moveToNext()){
int personid=cursor.getInt(cursor.getColumnIndex("personid"));
String name=cursor.getString(cursor.getColumnIndex("name"));
String phone=cursor.getString(cursor.getColumnIndex("phone"));
persons.add(new Person(personid,name,phone));
}
cursor.close();
return persons;
}


public long getCount(){
SQLiteDatabase db=dbOpenHelter.getReadableDatabase();
Cursor cursor=db.query("person", new String[]{"count(*)"}, null, 


null, null, null, null);
//Cursor cursor=db.rawQuery("select count(*) from person " 


,null);
//select count(*) from person注意这里至少会获得一条数据
cursor.moveToFirst();
long result=cursor.getLong(0);
return result;
}



}
---------------------------------------------------
/DBSQLIte/src/com/credream/test/OtherPersonServiceTest.java
package com.credream.test;


import java.util.List;


import com.credream.entity.Person;
import com.credream.service.DBOpenHelter;
import com.credream.service.OtherPersonService;
import com.credream.service.PersonService;


import android.test.AndroidTestCase;
import android.util.Log;


public class OtherPersonServiceTest extends AndroidTestCase
{
//PersonService service=new PersonService(this.getContext());
//不可以写到这里,因为这段代码是在实例化过程中被调用的,如果刚刚开始的就直


接实例化这个对象
//这时候是取不到上下文对象的,只有实例化过后才可以获取上下文对象
//如果非要把这个单独拿出来的话,可以写到setUp()方法里面,因为每个方法执行之


前都会首先执行这个方法
private static final String TAG="PersonServiceTest";
//创建数据库,在<包>/database/
public void testCreateDB()throws Exception{
DBOpenHelter dbOpenHelter=new DBOpenHelter(getContext());
dbOpenHelter.getWritableDatabase();
}
public void testSave()throws Exception{
OtherPersonService service=new OtherPersonService


(this.getContext());
//for(int i=0;i<20;i++){
//Person person=new Person("lidewei"+i,"15163245754"+i);
Person person=new Person("xiaoyue","15163245754");
service.save(person);
//}
}
public void testUpdate()throws Exception{
OtherPersonService service=new OtherPersonService


(this.getContext());
Person person=service.find(1);
person.setName("mydream");
service.update(person);

}


public void testDelete()throws Exception{
OtherPersonService service=new OtherPersonService


(this.getContext());
service.delete(22);
}


public void testFind()throws Exception{
OtherPersonService service=new OtherPersonService


(this.getContext());
Person person=service.find(1);
Log.i(TAG,person.toString());

}


public void testScrollData()throws Exception{
OtherPersonService service=new OtherPersonService


(this.getContext());
List<Person> persons=service.getScrollData(0, 50);
for(Person person :persons){
Log.i(TAG,person.toString());
}
//翻到第2页
}
public void testCount()throws Exception{
OtherPersonService service=new OtherPersonService


(this.getContext());
long result=service.getCount();
Log.i(TAG, result+"");

}
//除了以上的数据库操作为,还为我们提供了专门方法:



}
---------------------------------------------------------
/DBSQLIte/src/com/credream/service/DBOpenHelter.java
package com.credream.service;


import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;


public class DBOpenHelter extends SQLiteOpenHelper
{
//父类没有默认构造器,需要显示调用
public DBOpenHelter(Context context)
{
super(context, "credream.db", null, 2);
//数据库创建完成后,默认会保存在<包>/database/文件夹下
//当修改版本号时候,会触发:onUpgrade方法
//第二个:指定数据库名称,
//第三个:游标工厂,用来迭代,查询后的结果集,null代表使用系统默认的


游标工厂
//版本号,大于0
 
}
/**
 * 这个方法是在数据库第一次被创建的时候调用的
 */
@Override
public void onCreate(SQLiteDatabase db)
{
//SQLiteDatabase这个类,封装了增删改查操作,也叫做数据库操作实例
db.execSQL("CREATE TABLE person (personid integer primary key 


autoincrement, name varchar(20))");
//这里也可以不写name的数据类型,因为sqlite是数据类型无关的,就是写


了varchar(20),也可以写入超过20的内容

 
}
/**
 * 当数据库的版本号变更的时候被调用
 */
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("alter table person add phone varchar(12) null");


}


}
--------------------------------------------------------------  
原创粉丝点击