Kotlin is a statically typed programming language that is widely used in Android development. SQLite is a popular database engine that's perfect for small mobile applications. In this article, we'll go through how to insert records into an SQLite table using Kotlin.
Setting up Your SQLite Database
Before we dive into inserting records, you need to set up an SQLite database in your application. This involves creating a helper class that extends SQLiteOpenHelper. Let's start off by creating a database and table in Kotlin.
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class MyDatabaseHelper(context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
companion object {
const val DATABASE_NAME = "example.db"
const val DATABASE_VERSION = 1
const val TABLE_NAME = "users"
const val COLUMN_ID = "id"
const val COLUMN_NAME = "name"
const val COLUMN_EMAIL = "email"
}
override fun onCreate(db: SQLiteDatabase) {
val CREATE_USERS_TABLE = ("CREATE TABLE " + TABLE_NAME + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_NAME + " TEXT," +
COLUMN_EMAIL + " TEXT")")
db.execSQL(CREATE_USERS_TABLE)
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME)
onCreate(db)
}
}
Inserting Data into Your Table
Now that we have our database and table set up, we can proceed to insert some data. You'll utilize a writable database and ContentValues to add data.
import android.content.ContentValues
fun insertUser(name: String, email: String) {
val dbHelper = MyDatabaseHelper(context)
val db = dbHelper.writableDatabase
val values = ContentValues()
values.put(MyDatabaseHelper.COLUMN_NAME, name)
values.put(MyDatabaseHelper.COLUMN_EMAIL, email)
db.insert(MyDatabaseHelper.TABLE_NAME, null, values)
db.close()
}
In this code snippet, we create an instance of ContentValues and put our data into it. We then call db.insert(), which inserts the values into the table specified by MyDatabaseHelper.TABLE_NAME.
Full Workflow Example
Let's see how you can put it all together, including creating the database helper and inserting a new user record.
fun main() {
// Make sure your context is initialized, usually in an Android Application context
val context: Context = /* your context */
// Instantiate your database helper
val dbHelper = MyDatabaseHelper(context)
// Inserting data
insertUser("John Doe", "[email protected]")
println("User inserted")
}
Conclusion
Inserting records into an SQLite database in Kotlin is straightforward. Just define your helper class, perform writable operations, and use ContentValues for managing data. This allows your app to handle persistent data seamlessly.