Sling Academy
Home/Kotlin/Inserting Records into SQLite Tables Using Kotlin

Inserting Records into SQLite Tables Using Kotlin

Last updated: November 30, 2024

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.

Next Article: Querying SQLite Databases: Retrieving Data with Kotlin

Previous Article: Creating SQLite Tables Programmatically in Kotlin

Series: Kotlin - Interacting with Databases

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin