Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách sử dụng hàm PRINTF() trong SQLite Android

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

Dấu % chữ
SpecifierÝ nghĩaVí dụ
%sChuỗiPRINTF('Hello %s', 'World') → Hello World
%d / %iSố nguyênPRINTF('%d', 42) → 42
%fSố thực (mặc định 6 chữ số sau dấu)PRINTF('%f', 3.14) → 3.140000
%.2fSố thực 2 chữ số thập phânPRINTF('%.2f', 3.14159) → 3.14
%05dSố nguyên đệm 0 độ rộng 5PRINTF('%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 Java String.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).