sqliteHow do I use SQLite in an Android application?
Using SQLite in an Android application is an easy way to store data locally. It is a light-weight database that is built into the Android OS and can be used to store structured data.
The following is an example of how to create a database and a table in SQLite and insert some data into it:
// Create a database
SQLiteDatabase db = openOrCreateDatabase("myDB", MODE_PRIVATE, null);
// Create a table
db.execSQL("CREATE TABLE IF NOT EXISTS myTable (name VARCHAR, age INT(3))");
// Insert data
db.execSQL("INSERT INTO myTable (name, age) VALUES ('John', 30)");
Once the data has been inserted, it can be queried using the SELECT
statement:
// Query the data
Cursor cursor = db.rawQuery("SELECT * FROM myTable", null);
// Iterate through the result set
while (cursor.moveToNext()) {
String name = cursor.getString(0);
int age = cursor.getInt(1);
Log.d("Database", "Name: " + name + ", Age: " + age);
}
The output would be:
D/Database: Name: John, Age: 30
Code explanation
openOrCreateDatabase
- opens or creates a database with the given name and modedb.execSQL
- executes an SQL statementrawQuery
- executes a query and returns aCursor
objectcursor.moveToNext
- moves the cursor to the next rowcursor.getString
- returns the value of the given column index as aString
cursor.getInt
- returns the value of the given column index as anint
Log.d
- writes a log message
Helpful links
More of Sqlite
- How can SQLite and ZFS be used together for software development?
- How do I use SQLite transactions?
- How can I use SQLite to query for records between two specific dates?
- How do I use the SQLite ZIP VFS to compress a database?
- How do I use SQLite Expert Personal to create a database?
- How can I use SQLite with Xamarin?
- How to configure SQLite with XAMPP on Windows?
- How do I use SQLite with Visual Studio?
- How do I use SQLite to retrieve data from a specific year?
- How can I use SQLite with WPF?
See more codes...