SQLite Database
SQLite Database
SQLite គឺជា relational database engine តូចមួយដែល built-in នៅក្នុង Android។ វាមិនត្រូវការ server ហើយរក្សាទុកទិន្នន័យទាំងអស់នៅក្នុង single file!
🎯 SQLite Characteristics
Feature | Description |
---|---|
🗄️ Serverless | No separate server process needed |
📄 Single File | Entire database in one .db file |
⚡ Fast | Optimized for mobile devices |
💾 Size Limit | Up to ~2 GB (theoretical 140 TB) |
🔐 ACID | Atomic, Consistent, Isolated, Durable |
🏗️ Database Architecture
┌─────────────────────────────────┐ │ Your Activity/Fragment │ └────────────┬────────────────────┘ │ calls methods ┌────────────▼────────────────────┐ │ DatabaseHelper (extends │ ──► Manages DB lifecycle │ SQLiteOpenHelper) │ └────────────┬────────────────────┘ │ ┌────────────▼────────────────────┐ │ SQLiteDatabase │ ──► Provides CRUD methods └────────────┬────────────────────┘ │ ┌────────────▼────────────────────┐ │ MyDatabase.db │ ──► Physical file on disk │ /data/data/package/databases/ │ └─────────────────────────────────┘
📚 ជំហានប្រើ SQLite (5 Steps)
- 📝 បង្កើត DatabaseHelper class (extends SQLiteOpenHelper)
- 🏗️ កំណត់ table structure (column names, types)
- ✨ Implement onCreate() - Create tables
- 🔄 Implement onUpgrade() - Handle version changes
- ⚙️ CRUD operations - Create, Read, Update, Delete
📊 SQL Data Types
SQLite Type | Java Type | Example |
---|---|---|
INTEGER |
int, long | age, id, count |
TEXT |
String | name, email, address |
REAL |
float, double | price, score, rating |
BLOB |
byte[] | image, file data |
NULL |
null | null value |
⚡ Performance Optimization
Technique | Benefit | Speed Gain |
---|---|---|
🔢 Indexing | Fast SELECT queries | 10-100x faster |
💼 Transactions | Batch multiple operations | 100x faster (bulk insert) |
📝 Compiled Statements | Reuse prepared SQL | 5-10x faster |
🗜️ Normalize Tables | Reduce redundancy | Smaller database size |
🔄 Database Migration
នៅពេល database version ផ្លាស់ប្តូរ, onUpgrade()
ត្រូវបានហៅ:
Version 1 ──► users table (id, name) │ ▼ onUpgrade() │ Version 2 ──► users table (id, name, email) ← Added email column │ ▼ onUpgrade() │ Version 3 ──► users + posts tables ← Added new table
🆚 SQLite vs Room
Feature | SQLite (Raw) | Room (Recommended) |
---|---|---|
Boilerplate Code | ❌ Lots of code | ✅ Minimal code |
Compile-time Checks | ❌ Runtime errors | ✅ Compile-time verification |
Object Mapping | ❌ Manual (Cursor) | ✅ Automatic |
LiveData Support | ❌ No | ✅ Built-in |
Migrations | ⚠️ Manual complex code | ✅ Simplified |
Recommendation | Learning purposes | ✅ Production apps |
✅ Modern Approach: ប្រើ Room Database សម្រាប់ new projects! SQLite raw គឺសម្រាប់ understand fundamentals។
Java Code
Click "Run" to execute the Java code