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 do I use SQLite Studio to manage my database?
- How do I use SQLite xfilter to filter data?
- How to configure SQLite with XAMPP on Windows?
- How do I use the SQLite ZIP VFS to compress a database?
- How do I use a SQLite viewer to view my database?
- How do I install SQLite using Python?
- How do I use SQLite to update or insert data?
- How do I use SQLite with QML?
- How do I use SQLite UNION to combine multiple SELECT queries?
- How do I download and install SQLite zip?
See more codes...