Sử dụng SQLite trong android phần 2

4) Cách truy vấn dữ liệu trong bảng.
– Là thao tác phức tạp nhất trong truy suất SQLite
– Ta dùng Cursor để lưu trữ giá trị trả về của hàm dưới đây:
public Cursor query (String table, String[] columns, String selection, String[]selectionArgs, String groupBy, String having, String orderBy) 
Xem bảng mô tả chi tiết:
tableThe table name to compile the query against.
columnsA list of which columns to return. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn’t going to be used.
selectionA filter declaring which rows to return, formatted as an SQL WHERE clause (excluding the WHERE itself). Passing null will return all rows for the given table.
selectionArgsYou may include ?s in selection, which will be replaced by the values from selectionArgs, in order that they appear in the selection. The values will be bound as Strings.
groupByA filter declaring how to group rows, formatted as an SQL GROUP BY clause (excluding the GROUP BY itself). Passing null will cause the rows to not be grouped.
havingA filter declare which row groups to include in the cursor, if row grouping is being used, formatted as an SQL HAVING clause (excluding the HAVING itself). Passing null will cause all row groups to be included, and is required when row grouping is not being used.
orderByHow to order the rows, formatted as an SQL ORDER BY clause (excluding the ORDER BY itself). Passing null will use the default sort order, which may be unordered.
– Ở đây Tôi làm ví dụ đơn giản nhất là truy vấn không phải lọc theo điều kiện nào cả:
– Ví dụ đọc tất cả danh sách lớp học trong bảng tbllop:
31_sqlite_9
-database.query sẽ trả về một Cursor, Lúc này Cursor đầu đọc chưa trỏ tới dòng dữ liệu nào cả. Do đó ta phải gọi lệnh .moveToFirst để Cursor trỏ đầu đọc tới dòng đầu tiên. Sau đó ta dùng vòng lặp while để duyệt từng dòng dữ liệu. Chú ý là Cursor này giống như Pointer nó cho phép truy suất ngẫu nhiên.
– Bạn có thể tải coding mẫu đầy đủ của phần hướng dẫn này ở đây: http://www.mediafire.com/download/leuuld4a225tw5c/LearnSQLite.rar
– Bài tập tiếp theo Tôi sẽ yêu cầu các bạn viết chương trình quản lý sách sử dụng SQLite để bạn củng cố thêm kiến thức về nó.
– Chúc các bạn thành công.
Previous
Next Post »