package cn.itcast.service;
import android.content.Context;
import android.database.sqlite.sqliteDatabase;
import android.database.sqlite.sqliteOpenHelper;
public class DBOpenHelper extends sqliteOpenHelper {
private static final String DATABASENAME = "itcast.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);
}
}
首先通过上面的DBOpenHelper创建数据库,再实现操作数据库对象,代码如下:
package cn.itcast.service;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.sqliteDatabase;
import cn.itcast.domain.Person;
public class PersonService {
private DBOpenHelper dbOpenHelper;
public PersonService(Context context) {
this.dbOpenHelper = new DBOpenHelper(context);
}
public void save(Person person){
//如果要对数据进行更改,就调用此方法得到用于操作数据库的实例,该方法以读和写方式打开数据库
sqliteDatabase db = dbOpenHelper.getWritableDatabase();
db.execsql("insert into person (name) values(?)",new Object[]{person.getName()});
}
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"));
return new Person(personid,name);
}
return null;
}
public List<Person> getScrollData(Integer offset,Integer maxResult){
List<Person> persons = new ArrayList<Person>();
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")); Person person = new Person(personid,name); 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); } }