In this tutorial, we will learn how to connect to MySQL Database from Kotlin using JDBC with the help a Kotlin Example Program.

JDBC is the standard Java database connectivity API, and Kotlin can use it directly because Kotlin runs on the JVM. To connect Kotlin to MySQL, you need a MySQL Connector/J driver, a valid JDBC URL, database credentials, and code that opens and closes the connection safely.

Following is a step by step process explained to connect to MySQL Database from Kotlin using JDBC.

Kotlin MySQL JDBC Prerequisites Before Writing the Connection Code

Before running the Kotlin program, make sure that MySQL Server is installed and running, the database user has permission to connect, and the MySQL JDBC driver is available in the project classpath. The examples below assume that MySQL is running on 127.0.0.1 at port 3306.

  • Kotlin/JVM project: The code must run as a JVM application, not Kotlin/JS or Kotlin/Native.
  • MySQL Server: Use a local or remote MySQL server that accepts TCP connections.
  • MySQL user: Replace username and password with real credentials.
  • Connector/J driver: Add the MySQL JDBC driver using Gradle, Maven, or a downloaded JAR file.
  • Database URL: Use a JDBC URL such as jdbc:mysql://127.0.0.1:3306/studentsDB.

Step 1 : Add MySQL connector for java

MySQL connector for java works for Kotlin as well. Download MySQL connector for java, mysql-connector-java-5.1.42-bin.jar , from https://dev.mysql.com/downloads/connector/j/5.1.html. Open IntelliJ IDEA, Click on File in Menu, Click on Project Structure, Click on Libraries on the left panel, and add the jar to Libraries.

Add MySQL jar to Kotlin Java Runtime Library - Connect to MySQL Database from Kotlin using JDBC - Kotlin Tutorial
Add MySQL jar to Kotlin Java Runtime Library

The manual JAR method still helps when you are learning classpath setup in IntelliJ IDEA. For most current Kotlin projects, Gradle or Maven dependency management is easier because the build tool downloads the MySQL Connector/J dependency and keeps it available during compile and run tasks.

Add MySQL Connector/J in a Kotlin Gradle Project

If your Kotlin project uses Gradle Kotlin DSL, add the MySQL Connector/J dependency in build.gradle.kts. Use a current Connector/J version supported by your project and MySQL server. The dependency coordinates below show the usual Maven artifact name for modern Connector/J releases.

</>
Copy
dependencies {
    implementation("com.mysql:mysql-connector-j:8.4.0")
}

For a simple command-line Kotlin application, your Gradle file may look like this.

</>
Copy
plugins {
    kotlin("jvm") version "2.0.0"
    application
}

repositories {
    mavenCentral()
}

dependencies {
    implementation("com.mysql:mysql-connector-j:8.4.0")
}

application {
    mainClass.set("MainKt")
}

If you use Maven instead of Gradle, add the MySQL Connector/J dependency in pom.xml.

</>
Copy
<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Step 2 : Establish a connection to MySQL Server

To establish a connection to MySQL Server

  1. Prepare username and password as properties
  2. Use Class.forName() to create an instance for JDBC Driver.
  3. Use DriverManager.getConnection() to create a connection to the SQL server. The first argument to this function is the URL that specifies the location of MySQL server. The second argument has credentials to login to the server.
val connectionProps = Properties()
connectionProps.put("user", username)
connectionProps.put("password", password)
try {
    Class.forName("com.mysql.jdbc.Driver").newInstance()
    conn = DriverManager.getConnection(
            "jdbc:" + "mysql" + "://" +
                    "127.0.0.1" +
                    ":" + "3306" + "/" +
                    "",
            connectionProps)
} catch (ex: SQLException) {
    // handle any errors
    ex.printStackTrace()
} catch (ex: Exception) {
    // handle any errors
    ex.printStackTrace()
}

In recent MySQL Connector/J versions, the driver class is usually com.mysql.cj.jdbc.Driver. Also, when the driver dependency is correctly available in the classpath, JDBC can often load the driver automatically. Calling Class.forName() is still seen in many examples because it makes driver loading explicit.

A practical JDBC URL includes the database name. For example, to connect to a database named studentsDB, use this format:

</>
Copy
jdbc:mysql://127.0.0.1:3306/studentsDB

Modern Kotlin MySQL Connection Using DriverManager

The following Kotlin function opens a MySQL JDBC connection using DriverManager.getConnection(). It keeps the URL, username, and password clear so that you can replace them for your environment.

</>
Copy
import java.sql.Connection
import java.sql.DriverManager

fun openMySqlConnection(): Connection {
    val url = "jdbc:mysql://127.0.0.1:3306/studentsDB"
    val username = "root"
    val password = "your_password"

    // Optional with modern Connector/J when the driver is on the classpath.
    Class.forName("com.mysql.cj.jdbc.Driver")

    return DriverManager.getConnection(url, username, password)
}

For real applications, avoid hard-coding passwords in source code. Use environment variables, configuration files outside version control, or a secrets manager depending on how the application is deployed.

</>
Copy
val username = System.getenv("MYSQL_USER") ?: error("MYSQL_USER is not set")
val password = System.getenv("MYSQL_PASSWORD") ?: error("MYSQL_PASSWORD is not set")

Step 3 : Execute MySQL Query to show DATABASES available

var stmt: Statement? = null
var resultset: ResultSet? = null

try {
    stmt = conn!!.createStatement()
    resultset = stmt!!.executeQuery("SHOW DATABASES;")

    if (stmt.execute("SHOW DATABASES;")) {
        resultset = stmt.resultSet
    }

    while (resultset!!.next()) {
        println(resultset.getString("Database"))
    }
} catch (ex: SQLException) {
    // handle any errors
    ex.printStackTrace()
}

The above query lists databases that the connected MySQL user is allowed to see. If the user has limited privileges, the output may not show every database on the server.

Example 1 – Connect to MySQL Database from Kotlin using JDBC

The following program connects to a specific MySQL server and executes ‘SHOW DATABASES;’ query.

example.kt

</>
Copy
import java.sql.*
import java.util.Properties
 
/**
 * Program to list databases in MySQL using Kotlin
 */
object MySQLDatabaseExampleKotlin {
 
    internal var conn: Connection? = null
    internal var username = "username" // provide the username
    internal var password = "password" // provide the corresponding password
 
    @JvmStatic fun main(args: Array<String>) {
        // make a connection to MySQL Server
        getConnection()
        // execute the query via connection object
        executeMySQLQuery()
    }
 
    fun executeMySQLQuery() {
        var stmt: Statement? = null
        var resultset: ResultSet? = null
 
        try {
            stmt = conn!!.createStatement()
            resultset = stmt!!.executeQuery("SHOW DATABASES;")
 
            if (stmt.execute("SHOW DATABASES;")) {
                resultset = stmt.resultSet
            }
 
            while (resultset!!.next()) {
                println(resultset.getString("Database"))
            }
        } catch (ex: SQLException) {
            // handle any errors
            ex.printStackTrace()
        } finally {
            // release resources
            if (resultset != null) {
                try {
                    resultset.close()
                } catch (sqlEx: SQLException) {
                }
 
                resultset = null
            }
 
            if (stmt != null) {
                try {
                    stmt.close()
                } catch (sqlEx: SQLException) {
                }
 
                stmt = null
            }
 
            if (conn != null) {
                try {
                    conn!!.close()
                } catch (sqlEx: SQLException) {
                }
 
                conn = null
            }
        }
    }
 
    /**
     * This method makes a connection to MySQL Server
     * In this example, MySQL Server is running in the local host (so 127.0.0.1)
     * at the standard port 3306
     */
    fun getConnection() {
        val connectionProps = Properties()
        connectionProps.put("user", username)
        connectionProps.put("password", password)
        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance()
            conn = DriverManager.getConnection(
                    "jdbc:" + "mysql" + "://" +
                            "127.0.0.1" +
                            ":" + "3306" + "/" +
                            "",
                    connectionProps)
        } catch (ex: SQLException) {
            // handle any errors
            ex.printStackTrace()
        } catch (ex: Exception) {
            // handle any errors
            ex.printStackTrace()
        }
    }
}

Output

information_schema
mysql
performance_schema
studentsDB
sys

Example 2 – Kotlin JDBC Query with use Blocks to Close Resources

Kotlin’s use function is useful with JDBC because Connection, Statement, and ResultSet must be closed after use. The following example connects to a MySQL database, runs a SELECT query, and closes resources automatically.

</>
Copy
CREATE DATABASE studentsDB;

USE studentsDB;

CREATE TABLE students (
    id INT PRIMARY KEY AUTO_INCREMENT,
    name VARCHAR(100) NOT NULL,
    marks INT NOT NULL
);

INSERT INTO students (name, marks) VALUES
('Arun', 82),
('Meena', 91),
('Kiran', 76);

Main.kt

</>
Copy
import java.sql.DriverManager

fun main() {
    val url = "jdbc:mysql://127.0.0.1:3306/studentsDB"
    val username = "root"
    val password = "your_password"

    DriverManager.getConnection(url, username, password).use { connection ->
        connection.createStatement().use { statement ->
            statement.executeQuery("SELECT id, name, marks FROM students").use { resultSet ->
                while (resultSet.next()) {
                    val id = resultSet.getInt("id")
                    val name = resultSet.getString("name")
                    val marks = resultSet.getInt("marks")
                    println("$id - $name - $marks")
                }
            }
        }
    }
}

Output

1 - Arun - 82
2 - Meena - 91
3 - Kiran - 76

Example 3 – Insert Data into MySQL from Kotlin with PreparedStatement

Use PreparedStatement when values are supplied from variables, forms, files, or user input. It avoids manual string concatenation and helps prevent SQL injection errors.

</>
Copy
import java.sql.DriverManager

fun main() {
    val url = "jdbc:mysql://127.0.0.1:3306/studentsDB"
    val username = "root"
    val password = "your_password"

    val sql = "INSERT INTO students (name, marks) VALUES (?, ?)"

    DriverManager.getConnection(url, username, password).use { connection ->
        connection.prepareStatement(sql).use { preparedStatement ->
            preparedStatement.setString(1, "Lakshmi")
            preparedStatement.setInt(2, 88)

            val rowsInserted = preparedStatement.executeUpdate()
            println("Rows inserted: $rowsInserted")
        }
    }
}

Output

Rows inserted: 1

Kotlin MySQL JDBC URL Format and Common Connection Options

A MySQL JDBC URL starts with jdbc:mysql://, followed by the host, port, and database name. Optional parameters can be added after a question mark.

</>
Copy
jdbc:mysql://host:port/database_name?option1=value1&option2=value2
URL partExampleMeaning
Protocoljdbc:mysql://Tells JDBC to use the MySQL driver.
Host127.0.0.1MySQL server address. Use a remote hostname or IP for remote servers.
Port3306Default MySQL TCP port unless your server uses a different port.
DatabasestudentsDBDatabase schema to connect to.
OptionsserverTimezone=UTCDriver-specific connection options when needed.

For local learning, a simple URL is usually enough. In production, connection settings may also include SSL, time zone, character encoding, connection pooling, and server-specific options.

Troubleshooting Kotlin MySQL JDBC Connection Errors

Most Kotlin MySQL connection errors come from an unavailable driver, an incorrect JDBC URL, a stopped MySQL server, wrong credentials, or insufficient database privileges. The table below lists common errors and practical checks.

Error or symptomLikely reasonWhat to check
No suitable driver foundMySQL Connector/J is not in the classpath or dependency is missing.Add the Connector/J dependency in Gradle or Maven and refresh the project.
ClassNotFoundException: com.mysql.jdbc.DriverOld driver class name is used with a newer driver or driver is missing.Use com.mysql.cj.jdbc.Driver for modern Connector/J, or rely on automatic driver loading.
Access denied for userUsername, password, host, or privileges are incorrect.Test the same credentials in MySQL client and grant required privileges.
Communications link failureKotlin program cannot reach the MySQL server.Check host, port, firewall, Docker port mapping, and whether MySQL is running.
Empty or unexpected query outputUser has limited privileges or selected database/table has no matching data.Check grants, database name, table name, and query condition.

MySQL User Permission Example for Kotlin JDBC Testing

For testing, create a separate MySQL user instead of using the root account in application code. The following SQL creates a database, a user for local access, and grants permissions on that database.

</>
Copy
CREATE DATABASE studentsDB;

CREATE USER 'kotlin_user'@'localhost' IDENTIFIED BY 'strong_password_here';

GRANT ALL PRIVILEGES ON studentsDB.* TO 'kotlin_user'@'localhost';

FLUSH PRIVILEGES;

Then update the Kotlin connection values:

</>
Copy
val url = "jdbc:mysql://127.0.0.1:3306/studentsDB"
val username = "kotlin_user"
val password = "strong_password_here"

Kotlin JDBC Best Practices for MySQL Applications

  • Close JDBC resources: Use Kotlin use blocks for Connection, Statement, PreparedStatement, and ResultSet.
  • Prefer PreparedStatement: Do not build SQL by joining user input into strings.
  • Keep credentials outside source code: Use environment variables or deployment configuration.
  • Use a database-specific user: Avoid using the MySQL root account from application code.
  • Add a database name in the URL: It keeps queries clear and avoids accidental execution against the wrong schema.
  • Use connection pooling for server applications: For web apps and APIs, use a pool such as HikariCP instead of opening a new connection for every request.
  • Log errors carefully: Do not print database passwords or sensitive connection strings in logs.

Kotlin MySQL JDBC FAQ

How to connect to MySQL database from Kotlin using JDBC?

Add MySQL Connector/J to the Kotlin JVM project, create a JDBC URL such as jdbc:mysql://127.0.0.1:3306/studentsDB, and call DriverManager.getConnection(url, username, password). Then use Statement or PreparedStatement to run SQL queries.

Which MySQL JDBC driver class should be used in Kotlin?

For modern MySQL Connector/J versions, use com.mysql.cj.jdbc.Driver when explicitly loading the driver. Older examples may use com.mysql.jdbc.Driver. If the driver dependency is correctly available, JDBC can usually load the driver automatically.

Can Kotlin use Java JDBC libraries?

Yes. Kotlin/JVM can use Java JDBC libraries directly. Classes such as DriverManager, Connection, PreparedStatement, and ResultSet are Java classes, but they work normally in Kotlin code.

Why do I get No suitable driver found for jdbc:mysql?

This usually means MySQL Connector/J is missing from the runtime classpath or the Gradle/Maven dependency was not loaded. Add com.mysql:mysql-connector-j, refresh the project, and run the Kotlin application again.

Should I use Statement or PreparedStatement in Kotlin MySQL code?

Use Statement for simple fixed SQL examples, but use PreparedStatement when the query contains variable values. PreparedStatement handles parameters safely and is the better choice for insert, update, delete, and search queries that use input values.

Editorial QA Checklist for Kotlin MySQL JDBC Tutorial

  • Confirm that the tutorial explains both the legacy manual JAR setup and the current Gradle/Maven dependency approach for MySQL Connector/J.
  • Check that new Kotlin JDBC examples use com.mysql.cj.jdbc.Driver or driver auto-loading, while the older existing code blocks remain unchanged.
  • Verify that every MySQL connection example includes host, port, database name, username, and password placeholders that readers can replace.
  • Ensure that examples showing variable SQL values use PreparedStatement, not string concatenation.
  • Review troubleshooting notes for the common Kotlin MySQL errors: missing driver, wrong credentials, stopped server, wrong URL, and insufficient privileges.

Conclusion

In this Kotlin Tutorial, we have learnt to connect to MySQL Database from Kotlin using JDBC with the help of Kotlin Example Program.

The main points are: add MySQL Connector/J to the project, use a valid jdbc:mysql:// URL, open the connection through DriverManager, run SQL using Statement or PreparedStatement, and close JDBC resources after use.