BCA / B.Tech 14 min read

Working with Databases

Databases के साथ काम करना

Android में Databases का परिचय

जब आपको large amount of structured data (जैसे users की list, products, या records) को save करने की आवश्यकता होती है, तो files या SharedPreferences efficient नहीं होते हैं।

SQLite Database: Android structured data को store करने के लिए built-in support प्रदान करता है, जिसे SQLite database कहते हैं। SQLite एक lightweight, serverless, transactional SQL database engine है जो mobile devices के लिए perfect है।

यह data tables, rows, और columns में organized होता है और आप SQL (Structured Query Language) का उपयोग करके data को manage कर सकते हैं।

[Image of a simple database table structure]

Database के मुख्य Components

Android में database के साथ काम करने के लिए, आप `android.database.sqlite` package की classes का उपयोग करते हैं।

  • SQLiteOpenHelper: यह एक helper class है जो database creation और version management को handle करती है।
    • `onCreate(SQLiteDatabase db)`: यह तब call होता है जब database पहली बार बनाया जाता है। यहीं पर आप tables create करते हैं।
    • `onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)`: यह तब call होता है जब database version change होता है। इसका उपयोग tables को modify करने के लिए किया जाता है।
  • SQLiteDatabase: यह actual database object को represent करता है। आप इसका उपयोग SQL commands execute करने के लिए करते हैं (जैसे insert, update, delete, query)।
  • ContentValues: यह key-value pairs को store करता है। इसका उपयोग database में new row insert करने या existing row को update करने के लिए किया जाता है। Key column का नाम होता है।
  • Cursor: यह database query के result set को represent करता है। आप इसका उपयोग query से return हुए rows पर iterate करने के लिए करते हैं।

Database बनाने का उदाहरण (Example of Creating a Database)

Step 1: Database Helper Class बनाएं

एक नई Java class बनाएं जो `SQLiteOpenHelper` को extend करती हो।


public class DatabaseHelper extends SQLiteOpenHelper {
    // Database Info
    private static final String DATABASE_NAME = "UserManager.db";
    private static final int DATABASE_VERSION = 1;

    // Table Name
    private static final String TABLE_USERS = "users";

    // Table Columns
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_EMAIL = "email";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    // Called when the database is created for the first time
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_USERS_TABLE = "CREATE TABLE " + TABLE_USERS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," 
                + KEY_NAME + " TEXT,"
                + KEY_EMAIL + " TEXT" + ")";
        db.execSQL(CREATE_USERS_TABLE);
    }

    // Called when the database needs to be upgraded
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_USERS);
        // Create tables again
        onCreate(db);
    }
    
    // User को add करने के लिए method
    public void addUser(String name, String email) {
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, name);
        values.put(KEY_EMAIL, email);
        
        // Inserting Row
        db.insert(TABLE_USERS, null, values);
        db.close(); // Closing database connection
    }

    // सभी users को get करने के लिए method
    public Cursor getAllUsers() {
        SQLiteDatabase db = this.getReadableDatabase();
        return db.rawQuery("SELECT * FROM " + TABLE_USERS, null);
    }
}

Step 2: Activity में Helper का उपयोग करें


public class MainActivity extends AppCompatActivity {
    DatabaseHelper dbHelper;
    EditText nameEditText, emailEditText;
    TextView resultTextView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        dbHelper = new DatabaseHelper(this);
        nameEditText = findViewById(R.id.name_et);
        emailEditText = findViewById(R.id.email_et);
        resultTextView = findViewById(R.id.result_tv);
    }

    // Button click to add user
    public void addUserToDb(View view) {
        String name = nameEditText.getText().toString();
        String email = emailEditText.getText().toString();
        dbHelper.addUser(name, email);
        Toast.makeText(this, "User added!", Toast.LENGTH_SHORT).show();
    }
    
    // Button click to load users
    public void loadUsers(View view) {
        Cursor cursor = dbHelper.getAllUsers();
        StringBuilder stringBuilder = new StringBuilder();

        if (cursor.moveToFirst()) {
            do {
                int id = cursor.getInt(cursor.getColumnIndex(DatabaseHelper.KEY_ID));
                String name = cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_NAME));
                String email = cursor.getString(cursor.getColumnIndex(DatabaseHelper.KEY_EMAIL));
                stringBuilder.append("ID: ").append(id)
                             .append(", Name: ").append(name)
                             .append(", Email: ").append(email).append("
");
            } while (cursor.moveToNext());
        }
        cursor.close();
        resultTextView.setText(stringBuilder.toString());
    }
}