Giới thiệu về SQLite trong Android
SQLite là một cơ sở dữ liệu SQL mã nguồn mở, lưu trữ dữ liệu vào tệp văn bản trên thiết bị. Android tích hợp sẵn SQLite, hỗ trợ đầy đủ các tính năng của cơ sở dữ liệu quan hệ. Để truy cập cơ sở dữ liệu này, bạn không cần thiết lập kết nối như JDBC hay ODBC.
Ví dụ: Lọc dữ liệu cơ bản với WHERE
Hướng dẫn này minh họa cách sử dụng mệnh đề WHERE để lọc bản ghi theo điều kiện cụ thể (ví dụ: tên = 'Me').
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.
Bước 2: Thiết kế giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Nhập tên"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/salary"
android:layout_width="match_parent"
android:inputType="numberDecimal"
android:hint="Nhập lương"
android:layout_height="wrap_content" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button
android:id="@+id/save"
android:text="Lưu"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/refresh"
android:text="Làm mới"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</LinearLayout>
Bước 3: Code MainActivity.java
package com.example.andy.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Button save, refresh;
EditText name, salary;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final DatabaseHelper helper = new DatabaseHelper(this);
final ArrayList array_list = helper.getAllContacts();
name = findViewById(R.id.name);
salary = findViewById(R.id.salary);
listView = findViewById(R.id.listView);
final ArrayAdapter arrayAdapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, array_list);
listView.setAdapter(arrayAdapter);
findViewById(R.id.refresh).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
array_list.clear();
array_list.addAll(helper.getAllContacts());
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
listView.refreshDrawableState();
}
});
findViewById(R.id.save).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String nameStr = name.getText().toString().trim();
String salaryStr = salary.getText().toString().trim();
if (!nameStr.isEmpty() && !salaryStr.isEmpty()) {
if (helper.insert(nameStr, salaryStr)) {
Toast.makeText(MainActivity.this, "Đã thêm", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Không thêm được", Toast.LENGTH_LONG).show();
}
} else {
name.setError("Nhập TÊN");
salary.setError("Nhập LƯƠNG");
}
}
});
}
}
Bước 4: Code DatabaseHelper.java
package com.example.andy.myapplication;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import java.io.IOException;
import java.util.ArrayList;
class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "salaryDatabase3";
public static final String CONTACTS_TABLE_NAME = "SalaryDetails";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
try {
db.execSQL("create table " + CONTACTS_TABLE_NAME +
"(id INTEGER PRIMARY KEY, name text, salary text)");
} catch (SQLiteException e) {
try { throw new IOException(e); }
catch (IOException e1) { e1.printStackTrace(); }
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + CONTACTS_TABLE_NAME);
onCreate(db);
}
public boolean insert(String name, String salary) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("name", name);
contentValues.put("salary", salary);
db.insert(CONTACTS_TABLE_NAME, null, contentValues);
return true;
}
// Quan trọng: WHERE cơ bản - lọc name = 'Me'
public ArrayList getAllContacts() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList array_list = new ArrayList<>();
Cursor res = db.rawQuery(
"select * from " + CONTACTS_TABLE_NAME + " WHERE name = 'Me'", null);
res.moveToFirst();
while (!res.isAfterLast()) {
array_list.add(res.getString(res.getColumnIndex("name")));
res.moveToNext();
}
return array_list;
}
}
Chạy ứng dụng
Kết nối thiết bị Android thật với máy tính. Trong Android Studio, mở file activity và nhấn biểu tượng Run. Chọn thiết bị di động và kiểm tra màn hình hiển thị.

Kết quả hiển thị "Me" trong ListView vì truy vấn lọc với điều kiện WHERE name = 'Me'.
Giải thích mệnh đề WHERE
WHERE dùng để lọc các hàng (rows) thỏa mãn điều kiện trước khi trả về kết quả.
Cú pháp cơ bản
SELECT column1, column2, ... FROM table_name WHERE condition;
Các toán tử thường dùng trong WHERE
| Loại | Toán tử | Mô tả | Ví dụ |
|---|---|---|---|
| So sánh | = | Bằng | name = 'John' |
| !=, <> | Khác | age != 18 | |
| > | Lớn hơn | salary > 5000 | |
| < | Nhỏ hơn | age < 30 | |
| >= | Lớn hơn hoặc bằng | score >= 60 | |
| <= | Nhỏ hơn hoặc bằng | price <= 100 | |
| Logic | AND | Cả hai đúng | age > 18 AND active = 1 |
| OR | Ít nhất một đúng | role = 'admin' OR role = 'mod' | |
| NOT | Phủ định | NOT (status = 'deleted') | |
| IS / IS NOT | Kiểm tra NULL | email IS NULL | |
| Khác | LIKE | Khớp mẫu (% _) | name LIKE 'J%' |
| IN | Trong danh sách | id IN (1,2,3) | |
| BETWEEN | Trong khoảng | age BETWEEN 18 AND 65 | |
| EXISTS | Tồn tại subquery | EXISTS (SELECT 1 FROM orders WHERE user_id = users.id) | |
| GLOB | Khớp mẫu Unix | name GLOB '*[0-9]*' |
Ví dụ thực tế
-- Tìm nhân viên IT lương > 1000 SELECT * FROM employees WHERE dept = 'IT' AND salary > 1000; -- Tìm user active hoặc pending, tạo sau 2023 SELECT * FROM users WHERE (status = 'active' OR status = 'pending') AND created_at > '2023-01-01'; -- Tìm email chưa xác thực SELECT * FROM users WHERE email_verified IS NOT TRUE; -- Tìm sản phẩm tên chứa "phone" SELECT * FROM products WHERE name LIKE '%phone%';
Best Practice: Parameterized Query (An toàn, tránh SQL Injection)
// ❌ KHÔNG AN TOÀN - nối chuỗi
String sql = "SELECT * FROM users WHERE name = '" + userInput + "'";
// ✅ AN TOÀN - dùng tham số
String sql = "SELECT * FROM users WHERE name = ?";
String[] args = { userInput };
Cursor cursor = db.rawQuery(sql, args);
// Hoặc dùng query() helper
Cursor cursor = db.query(
"users", // table
null, // columns (null = all)
"name = ?", // selection (WHERE)
new String[]{userInput}, // selectionArgs
null, // groupBy
null, // having
null // orderBy
);