Hàm PRINTF() trong SQLite
PRINTF(format, args...) định dạng chuỗi theo kiểu C printf. Hỗ trợ: %d (int), %f (float), %s (string), %.2f (2 chữ số thập phân), %05d (đệm 0), v.v.
Ví dụ: Định dạng hiển thị tên
DatabaseHelper.java
package com.example.printfdemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.ArrayList;
class DatabaseHelper extends SQLiteOpenHelper {
static final String DB_NAME = "salaryDatabase";
static final String TABLE = "SalaryDetails";
DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE +
"(id INTEGER PRIMARY KEY, name TEXT, salary REAL, datetime DEFAULT CURRENT_TIMESTAMP)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int old, int n) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE);
onCreate(db);
}
boolean insert(String name, String salary) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("salary", salary);
db.insert(TABLE, null, cv);
return true;
}
// PRINTF() định dạng chuỗi đầu ra
ArrayList<String> getAllContacts() {
ArrayList<String> list = new ArrayList<>();
SQLiteDatabase db = getReadableDatabase();
// Ví dụ: "Name: [sairam], Salary: [1500.50]"
Cursor c = db.rawQuery(
"SELECT PRINTF('Name: [%s], Salary: [%.2f]', name, salary) AS fullname FROM " + TABLE, null);
if (c.moveToFirst()) {
do {
list.add(c.getString(c.getColumnIndexOrThrow("fullname")));
} while (c.moveToNext());
}
c.close();
return list;
}
boolean update(String name, String salary) {
SQLiteDatabase db = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("salary", salary);
db.update(TABLE, cv, "name=?", new String[]{name});
return true;
}
boolean delete() {
getWritableDatabase().delete(TABLE, null, null);
return true;
}
}
Kết quả
Dữ liệu: (name="sairam", salary=1500.5)
ListView hiển thị: Name: [sairam], Salary: [1500.50]
Các format specifier phổ biến
| Specifier | Ý nghĩa | Ví dụ |
|---|---|---|
%s | Chuỗi | PRINTF('Hello %s', 'World') → Hello World |
%d / %i | Số nguyên | PRINTF('%d', 42) → 42 |
%f | Số thực (mặc định 6 chữ số sau dấu) | PRINTF('%f', 3.14) → 3.140000 |
%.2f | Số thực 2 chữ số thập phân | PRINTF('%.2f', 3.14159) → 3.14 |
%05d | Số nguyên đệm 0 độ rộng 5 | PRINTF('%05d', 7) → 00007 |
%% | PRINTF('100%%') → 100% |
Ứng dụng thực tế
- Xuất báo cáo CSV/JSON từ SQL thuần.
- Định dạng tiền tệ:
PRINTF('$%.2f', amount). - Tạo ID có đệm 0:
PRINTF('USER_%06d', id)→USER_000042. - Ghép chuỗi phức tạp thay cho
||.
Lưu ý
- SQLite
PRINTF()khác với JavaString.format()- chạy ở tầng SQL. - Hiệu năng tốt hơn format ở Java khi xử lý hàng nghìn dòng.
- Null argument → kết quả NULL (trừ %s thành chuỗi rỗng).