在Android中使用SQLite数据库进行查询操作时,可以使用SQLiteDatabase类中的query()方法来执行查询操作。以下是一个简单的示例代码:
// 创建SQLiteOpenHelper的子类来管理数据库的创建和版本升级
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "mydatabase.db";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_NAME = "mytable";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT)";
db.execSQL(createTableQuery);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public Cursor queryData() {
SQLiteDatabase db = this.getReadableDatabase();
String[] projection = {
COLUMN_ID,
COLUMN_NAME
};
Cursor cursor = db.query(
TABLE_NAME,
projection,
null,
null,
null,
null,
null
);
return cursor;
}
}
在上面的代码中,首先创建一个DatabaseHelper类继承自SQLiteOpenHelper类,其中定义了数据库名称、版本、表名和列名等常量。在onCreate()方法中创建表格,然后在queryData()方法中执行查询操作。
在Activity中使用该DatabaseHelper类进行查询操作:
DatabaseHelper dbHelper = new DatabaseHelper(this);
Cursor cursor = dbHelper.queryData();
if (cursor != null && cursor.moveToFirst()) {
do {
int id = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID));
String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME));
Log.d("Query Result", "ID: " + id + ", Name: " + name);
} while (cursor.moveToNext());
}
cursor.close();
dbHelper.close();
在Activity中创建DatabaseHelper对象,并调用queryData()方法获取Cursor对象,然后遍历Cursor对象获取查询结果。最后关闭Cursor和DatabaseHelper对象。
请注意在使用完Cursor对象和DatabaseHelper对象后记得调用close()方法释放资源。