Sling Academy
Home/Kotlin/Kotlin: Updating and Deleting Records Using JDBC

Kotlin: Updating and Deleting Records Using JDBC

Last updated: December 05, 2024

Kotlin is a modern programming language that has gained popularity for its clean syntax and full compatibility with Java. When working with databases in Kotlin, the Java Database Connectivity (JDBC) API provides a crucial link for executing SQL statements. In this article, we'll explore how you can update and delete database records using JDBC in Kotlin.

Setting Up Your Kotlin Project

To get started, ensure you have a Kotlin project ready with JDBC dependencies included. In your build.gradle.kts file, add the JDBC driver dependency specific to your database. For example, for a MySQL database, you would include:


dependencies {
    implementation("mysql:mysql-connector-java:8.0.30")
}

Now that your environment is set up, we'll proceed with the necessary steps to update and delete records.

Establishing a Database Connection

Using JDBC involves establishing a connection to the database first. We'll create a function to manage the database connection. Below is a simple example:


import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException

fun getConnection(): Connection? {
    val jdbcUrl = "jdbc:mysql://localhost:3306/your_database"
    val username = "your_username"
    val password = "your_password"

    return try {
        DriverManager.getConnection(jdbcUrl, username, password)
    } catch (e: SQLException) {
        e.printStackTrace()
        null
    }
}

Replace your_database, your_username, and your_password with your actual database details.

Updating Records

To update records in a database table, we use the SQL UPDATE statement. Below is an example of how to perform an update using JDBC in Kotlin:


fun updateRecord(connection: Connection, id: Int, newName: String): Boolean {
    val updateSQL = "UPDATE employees SET name = ? WHERE id = ?"
    return try {
        connection.prepareStatement(updateSQL).use { preparedStatement ->
            preparedStatement.setString(1, newName)
            preparedStatement.setInt(2, id)
            preparedStatement.executeUpdate() > 0
        }
    } catch (e: SQLException) {
        e.printStackTrace()
        false
    }
}

This function prepares an SQL statement to update the name of an employee. It uses placeholders (?) to avoid SQL injection risks and requires the new name and employee ID as inputs.

Deleting Records

Deleting records follows a similar pattern but uses the SQL DELETE statement:


fun deleteRecord(connection: Connection, id: Int): Boolean {
    val deleteSQL = "DELETE FROM employees WHERE id = ?"
    return try {
        connection.prepareStatement(deleteSQL).use { preparedStatement ->
            preparedStatement.setInt(1, id)
            preparedStatement.executeUpdate() > 0
        }
    } catch (e: SQLException) {
        e.printStackTrace()
        false
    }
}

In this function, DELETE FROM employees removes the employee corresponding to the specified ID.

Closing the Connection

After completing operations, it's crucial to close the JDBC connection to free resources. Typically, this is done in a finally block or using Kotlin's use function which automatically handles closing:


fun closeConnection(connection: Connection?) {
    connection?.close()
}

Make sure you manage exceptions diligently to prevent resource leaks and handle database-specific exceptions.

Putting It All Together

Here’s how you could use the above functions in your main function:


fun main() {
    val connection = getConnection() ?: return

    val updated = updateRecord(connection, 1, "John Doe")
    if (updated) {
        println("Record updated successfully.")
    } else {
        println("Failed to update record.")
    }

    val deleted = deleteRecord(connection, 2)
    if (deleted) {
        println("Record deleted successfully.")
    } else {
        println("Failed to delete record.")
    }

    closeConnection(connection)
}

With these techniques, you can effectively manage your database records using Kotlin and JDBC. As you proceed, explore error handling and potentially switching to async programming if your operations become slow or your application grows more complex.

Next Article: Working with Transactions in JDBC for Kotlin

Previous Article: Fetching Data with JDBC ResultSets 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