1.SQLiteOpenHelper使用方法
getReadableDatabase() //创建或打开一个只读的数据库
getWriteableDatabase() //创建或打开一个可读写的数据库
onCreate(SQLiteDatabase db) //创建数据库
onOpen(SQLiteDatabase db) //打开数据库
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) //更新数据库
close() //关闭数据库
2.在SQLOpenHelper的子类中,必须有该构造函数
public DBOpenHelper(Context context, String name, CursorFactory factory, int version)
//创建和更新数据库
public class DBOpenHelper extends SQLiteOpenHelper {
private static final String DATABASENAME = "sample.db"; //数据库名称
private static final int DATABASEVERSION = 1;//数据库版本
public DBOpenHelper(Context context) {
super(context, DATABASENAME, null, DATABASEVERSION);
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE person (personid integer primary key autoincrement, name varchar(20), amount integer)");//执行有更改的sql语句
}
//数据库版本或表结构改变会被调用
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS person");
onCreate(db);
}
}
2.使用execSQL和rawQuery语句对数据库增、删、改、查、分页和统计的操作
public class PersonService {
private DBOpenHelper dbOpenHelper;
public PersonService(Context context) {
this.dbOpenHelper = new DBOpenHelper(context);
}
public void payment(){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.beginTransaction();
try{
db.execSQL("update person set amount=amount-10 where personid=?", new Object[]{1});
db.execSQL("update person set amount=amount+10 where personid=?", new Object[]{2});
db.setTransactionSuccessful();
}finally{
db.endTransaction();
}
}
//添加的操作
public void save(Person person){
//如果要对数据进行更改,就调用此方法得到用于操作数据库的实例,该方法以读和写方式打开数据库
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("insert into person (name,amount) values(?,?)", new Object[]{person.getName(),person.getAmount()});
}
//更新的操作
public void update(Person person){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("update person set name=? where personid=?",
new Object[]{person.getName(),person.getId()});
}
//删除的操作
public void delete(Integer id){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.execSQL("delete from person where personid=?", new Object[]{id.toString()});
}
//查找的操作
public Person find(Integer id){
//如果只对数据进行读取,建议使用此方法
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
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"));
int amount = cursor.getInt(cursor.getColumnIndex("amount"));
Person person = new Person(personid, name);
person.setAmount(amount);
return person;
}
return null;
}
//分页的操作
public List getScrollData(Integer offset, Integer maxResult){
List persons = new ArrayList();
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from person limit ?,?",
new String[]{offset.toString(), maxResult.toString()});
while(cursor.moveToNext()){
int personid = cursor.getInt(cursor.getColumnIndex("personid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int amount = cursor.getInt(cursor.getColumnIndex("amount"));
Person person = new Person(personid, name);
person.setAmount(amount);
persons.add(person);
}
cursor.close();
return persons;
}
//对数据库表数据的统计操作
public long getCount() {
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select count(*) from person", null);
cursor.moveToFirst();
return cursor.getLong(0);
}
}
使用SQLiteDatabase所提供专门对SQLite进行添删改查的方法操作insert(),delete(),update(),query().
public class OtherPersonService {
private DBOpenHelper dbOpenHelper;
public OtherPersonService(Context context) {
this.dbOpenHelper = new DBOpenHelper(context);
}
public void save(Person person){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", person.getName());
db.insert("person", null, values);
}
public void update(Person person){
// update person set name =? where personid =?
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", person.getName());
db.update("person", values, "personid=?", new String[]{person.getId().toString()});
}
public void delete(Integer id){
SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
db.delete("person", "personid=?", new String[]{id.toString()});
}
public Person find(Integer id){
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.query("person", new String[]{"personid", "name"},
"personid=?", new String[]{id.toString()}, null, null, null);
//select personid,name from person where personid=? order by ... limit 3,5
if(cursor.moveToFirst()){
int personid = cursor.getInt(cursor.getColumnIndex("personid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
return new Person(personid, name);
}
return null;
}
public List getScrollData(Integer offset, Integer maxResult){
List persons = new ArrayList();
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.query("person", null, null, null, null, null, null, offset+","+ maxResult);
while(cursor.moveToNext()){
int personid = cursor.getInt(cursor.getColumnIndex("personid"));
String name = cursor.getString(cursor.getColumnIndex("name"));
Person person = new Person(personid, name);
persons.add(person);
}
cursor.close();
return persons;
}
public long getCount() {// select count(*) from person
SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
Cursor cursor = db.query("person", new String[]{"count(*)"}, null, null, null, null, null);
cursor.moveToFirst();
return cursor.getLong(0);
}
}
业务bean person类
public class Person {
private Integer id;
private String name;
private Integer amount;
public Integer getAmount() {
return amount;
}
public void setAmount(Integer amount) {
this.amount = amount;
}
public Person(){}
public Person(Integer id, String name) {
this.id = id;
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", amount=" + amount
+ "]";
}
}
3.数据库作为内容提供者实现对外共享
1.当应用需要通过ContentProvider对外共享数据时,第一步需要继承ContentProvider并重写下面方法:
public class PersonContentProvider extends ContentProvider{
public boolean onCreate()
public Uri insert(Uri uri, ContentValues values)
public int delete(Uri uri, String selection, String[] selectionArgs)
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
public String getType(Uri uri)}
2.需要在AndroidManifest.xml使用
3.使用ContentProvider共享数据的方法
public boolean onCreate()
该方法在ContentProvider创建后就会被调用, ContentProvider在其它应用第一次访问它时才会被创建。
public Uri insert(Uri uri, ContentValues values)
该方法用于供外部应用往ContentProvider添加数据。
public int delete(Uri uri, String selection, String[] selectionArgs)
该方法用于供外部应用从ContentProvider删除数据。
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
该方法用于供外部应用更新ContentProvider中的数据。
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
该方法用于供外部应用从ContentProvider中获取数据。
public String getType(Uri uri)
该方法用于返回当前Url所代表数据的MIME类型。如果操作的数据属于集合类型,那么MIME类型字符串应该以vnd.android.cursor.dir/开头,例如:要得到所有person记录的Uri为content://cn.sample.provider.personprovider/person,那么返回的MIME类型字符串应该为:“vnd.android.cursor.dir/person”。如果要操作的数据属于非集合类型数据,那么MIME类型字符串应该以vnd.android.cursor.item/开头,例如:得到id为10的person记录,Uri为content://cn.sample.provider.personprovider/person/10,那么返回的MIME类型字符串应该为:“vnd.android.cursor.item/person”。
4.使用ContentResolver操作ContentProvider中的数据
当外部应用需要对ContentProvider中的数据进行添加、删除、修改和查询操作时,可以使用ContentResolver 类来完成,要获取ContentResolver 对象,可以使用Activity提供的getContentResolver()方法。 ContentResolver 类提供了与ContentProvider类相同签名的四个方法:
public Uri insert(Uri uri, ContentValues values)
该方法用于往ContentProvider添加数据。
public int delete(Uri uri, String selection, String[] selectionArgs)
该方法用于从ContentProvider删除数据。
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs)
该方法用于更新ContentProvider中的数据。
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)
该方法用于从ContentProvider中获取数据。
这些方法的第一个参数为Uri,代表要操作的ContentProvider和对其中的什么数据进行操作,假设给定的是: Uri.parse(“content://cn.sample.providers.personprovider/person/10”),那么将会对主机名为cn.sample.providers.personprovider的ContentProvider进行操作,操作的数据为person表中id为10的记录。
ContentResolver resolver = getContentResolver();
Uri uri = Uri.parse("content://cn.sample.provider.personprovider/person");
//添加一条记录
ContentValues values = new ContentValues();
values.put("name", "liming");
values.put("age", 25);
resolver.insert(uri, values);
//获取person表中所有记录
Cursor cursor = resolver.query(uri, null, null, null, "personid desc");
while(cursor.moveToNext()){
Log.i("ContentTest", "personid="+ cursor.getInt(0)+ ",name="+ cursor.getString(1));
}
//把id为1的记录的name字段值更改新为liming
ContentValues updateValues = new ContentValues();
updateValues.put("name", "lisi");
Uri updateIdUri = ContentUris.withAppendedId(uri, 2);
resolver.update(updateIdUri, updateValues, null, null);
//删除id为2的记录
Uri deleteIdUri = ContentUris.withAppendedId(uri, 2);
resolver.delete(deleteIdUri, null, null);
5.ContentProvider使用实例
public class PersonProvider extends ContentProvider {
private DBOpenHelper dbOpenHelper;
private static final UriMatcher MATCHER=new UriMatcher(UriMatcher.NO_MATCH);
private static final int PERSONS=1;
private static final int PERSON=2;
static{
MATCHER.addURI("cn.sample.providers.personprovider", "person", PERSONS);
MATCHER.addURI("cn.sample.providers.personprovider", "person/#", PERSON);
}
//往ContentProvider(数据库)删除数据
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
int count=0;
switch(MATCHER.match(uri)){
case PERSONS:
count=db.delete("person", selection, selectionArgs);
return count;
case PERSON:
long id=ContentUris.parseId(uri);
String where="personid="+id;
if(selection!=null&&!"".equals(selection)){
where=selection+"and"+where;
}
count=db.delete("person", where, selectionArgs);
return count;
default:
throw new IllegalArgumentException("Unknow Uri:"+uri.toString());
}
}
@Override
public String getType(Uri uri) {
switch(MATCHER.match(uri)){
case PERSONS:
return "vnd.android.cursor.dir/person";
case PERSON:
return "vnd.android.cursor.item/person";
default:
throw new IllegalArgumentException("Unknow Uri:"+uri.toString());
}
}
//往ContentProvider添加数据
@Override
public Uri insert(Uri uri, ContentValues values) {
SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
switch(MATCHER.match(uri)){
case PERSONS:
Long rovid=db.insert("person","name", values);
Uri insertUri=ContentUris.withAppendedId(uri, rovid);
this.getContext().getContentResolver().notifyChange(uri, null);
return insertUri;
default:
throw new IllegalArgumentException("Unknow Uri:"+uri.toString());
}
}
@Override
public boolean onCreate() {
this.dbOpenHelper=new DBOpenHelper(this.getContext());
return false;
}
//往ContentProvider查询数据
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
switch(MATCHER.match(uri)){
case PERSONS:
return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
case PERSON:
long id=ContentUris.parseId(uri);
String where="personid="+id;
if(selection!=null&&!"".equals(selection)){
where=selection+"and"+where;
}
return db.query("person", projection, selection, selectionArgs, null, null, sortOrder);
default:
throw new IllegalArgumentException("Unknow Uri:"+uri.toString());
}
}
//往ContentProvider更新数据
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
SQLiteDatabase db=dbOpenHelper.getWritableDatabase();
int count=0;
switch(MATCHER.match(uri)){
case PERSONS:
count=db.update("person", values, selection, selectionArgs);
return count;
case PERSON:
long id=ContentUris.parseId(uri);
String where="personid="+id;
if(selection!=null&&!"".equals(selection)){
where=selection+"and"+where;
}
count=db.update("person", values, where, selectionArgs);
return count;
default:
throw new IllegalArgumentException("Unknow Uri:"+uri.toString());
}
}
}
UI类
public class MainActivity extends Activity {
private PersonService personService;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.personService=new PersonService(this);
Button button=(Button)this.findViewById(R.id.insertbutton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
ContentResolver contentresolver=getContentResolver();
Uri insertUri=Uri.parse("content://cn.sample.providers.personprovider/person");
ContentValues values=new ContentValues();
contentresolver.insert(insertUri, values);
values.put("name", "zhangsan");
values.put("amount", "20");
Uri uri=contentresolver.insert(insertUri, values);
Toast.makeText(MainActivity.this, "添加完成", 1).show();
}
});
}
}
AndroidManifest.xml文件实现代码