日期:2014-05-16 浏览次数:20411 次
在android中查询sqlite数据库,我们一般都是写一个继承SQLiteOpenHelper的工具类,然后实例化SQLiteDatabase对象去进行各种增删改查的操作,对于查询出来的结果,我们一般都放在google封装好的Cursor(游标)中,然后从Cursor中取出我们查询语句的value结果,过程类似这样:
public int getId(String name) { int id = 0; SQLiteDatabase db = getReadableDatabase(); if (db.isOpen() && !db.isDbLockedByOtherThreads()) { String sql = "SELECT id from cursor where name = '" + name + "'"; Cursor cursor = db.rawQuery(sql, null); while (cursor.moveToNext()) { id = cursor.getInt(cursor.getColumnIndex("id")); } if (cursor != null) { cursor.close(); } } if (db != null) { db.close(); } return id; }当我们想求得某一列所有数据之和时,我们一般采用这种方法:
public int getSum(){ int sum = 0; SQLiteDatabase db = getReadableDatabase(); if(db.isOpen() && !db.isDbLockedByOtherThreads()){ String sql = "SELECT id FROM people"; Cursor cursor = db.rawQuery(sql, null); while(cursor.moveToNext()){ sum += cursor.getInt(cursor.getColumnIndex("id")); } if(cursor != null){ cursor.close(); } } if(db != null){ db.close(); } return sum; }
public int getSum(){ int sum =0; SQLiteDatabase db = getReadableDatabase(); if(db.isOpen() && !db.isDbLockedByOtherThreads()){ String sql = "SELECT SUM(id) AS sum from people"; Cursor cursor = db.rawQuery(sql, null); while(cursor.moveToNext()){ sum = cursor.getInt(cursor.getColumnIndex("sum")); } if(cursor != null){ cursor.close(); } } if(db != null){ db.close(); } return sum; }
<