How to create a database
To create a SQLite database in Android using Java, follow these steps:
- Create a subclass of SQLiteOpenHelper: The SQLiteOpenHelper class is a helper class in Android that manages database creation and version management.
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "Student.db";
public static final String TABLE_NAME = "student_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NAME";
public static final String COL_3 = "MARKS";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT, MARKS INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+TABLE_NAME);
onCreate(db);
}
}
- Instantiate the helper class: Use the helper class to create and manage the database.
DatabaseHelper myDb = new DatabaseHelper(this);
- Add data to the database: Use the
getWritableDatabase()method to create an instance of the SQLiteDatabase class. Then use itsinsert()method to add data to the database.
SQLiteDatabase db = myDb.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("NAME", "John");
contentValues.put("MARKS", 95);
long result = db.insert("student_table", null ,contentValues);
- Query the database: Use the
getReadableDatabase()method to get an instance of the SQLiteDatabase class. Then use itsquery()method to retrieve data from the database.
SQLiteDatabase db = myDb.getReadableDatabase();
Cursor res = db.rawQuery( "select * from student_table", null );