Android sqlite 操作

今天开始写博客,写sqlite的基本应用的两个类,包含了基本的CRUD和分页操作。废话不说,代码能直接拷用。参照黎活明老师的讲解

 

 

public class dataBaseHelper extends SQLiteOpenHelper {

 private static final String DBNAME = "shining"; //数据库名称

  private static final int VERSION = 1; //数据库版本

public dataBaseHelper(Context context) {

super(context, DBNAME, null, VERSION);

// TODO Auto-generated constructor stub

}

 

@Override

public void onCreate(SQLiteDatabase db) {

// TODO Auto-generated method stub

//好友:id,name,age,phone

db.execSQL("CREATE TABLE IF NOT EXISTS friends(id integer primary key autoincrement, name varchar(20), age INTEGER,phone varchar(20))");

}

 

@Override

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

// TODO Auto-generated method stub

   db.execSQL("DROP TABLE IF EXISTS friends");

        onCreate(db);

}

 

}


 

 

 

 

public class FriendService {

 

 

private dataBaseHelper dbHelper;

public FriendService( Context context)

{

 

dbHelper=new dataBaseHelper(context);

}

public void save(Friend f)

{

SQLiteDatabase db=dbHelper.getWritableDatabase();

db.execSQL("insert into friends(name,age,phone) values(?,?,?)",new Object[]{f.getName(),f.getAge(),f.getPhone()});

db.close();

}

public void update(Friend f)

{

SQLiteDatabase db=dbHelper.getWritableDatabase();

db.execSQL("update friends set name=?,age=?,phone=? where id=?",

new Object[]{f.getName(),f.getAge(),f.getPhone(),f.getId()});

db.close();

}

public Friend find(int id)

{

SQLiteDatabase db=dbHelper.getReadableDatabase();

Cursor cursor=db.rawQuery("select * from friends where id=?",new String[]{String.valueOf(id)});

if(cursor.moveToNext())

{

   return new Friend(cursor.getInt(0),cursor.getString(1), cursor.getInt(2), cursor.getString(3));

   

}

db.close();

return null;

}

public void delete(Integer ...ids)

{

if(ids.length>0)

{

StringBuilder sb=new StringBuilder();

for(int i=0;i<ids.length;i++)

{

sb.append('?').append(',');

}

sb.deleteCharAt(sb.length()-1);

SQLiteDatabase db=dbHelper.getWritableDatabase();

db.execSQL("delete from friends where id in("+sb+")",(Object[])ids);

db.close();

}

}

public List<Friend> getList(int start,int max)

{

List<Friend> list=new ArrayList<Friend>();

SQLiteDatabase db=dbHelper.getWritableDatabase();

Cursor cursor=db.rawQuery("select * from friends limit ?,? ",new String[]{String.valueOf(start),String.valueOf(max)});

while(cursor.moveToNext())

{

list.add(new Friend(cursor.getInt(0),cursor.getString(1), cursor.getInt(2), cursor.getString(3)));

   

}

db.close();

return list;

}

public long getCount()

{

SQLiteDatabase db=dbHelper.getReadableDatabase();

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

if(cursor.moveToNext())

{

  return cursor.getLong(0);

   

}

db.close();

return 0;

}

}


 

 

 

你可能感兴趣的:(android,sqlite,F#)