How to connect to MySQL Database from Kotlin using JDBC
Kotlin Tutorial – We shall learn to connect to MySQL Database from Kotlin using JDBC with the help a Kotlin
Example Program.
Following is a step by step process explained to connect to MySQL Database from Kotlin using JDBC :
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
Step 2 : Establish a connection to MySQL 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()
}
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()
}
Kotlin Example Program to connect to MySQL Database from Kotlin using
JDBC
Example Kotlin program to connect to MySQL database using JDBC
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) {
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()
}
}
}
Program Output
information_schema
mysql
performance_schema
studentsDB
sys
Conclusion :
In this Kotlin Tutorial, we have learnt to connect to MySQL Database from Kotlin using JDBC with the help of
Kotlin Example Program.
Kotlin Java
Kotlin Tutorial
Getting Started
Kotlin - Setup Kotlin(Java) Project
Kotlin - Basic Program Example
Kotlin - Convert Java File to Kotlin File
Kotlin - Main Function
Kotlin for loop, forEach
Kotlin while, do-while loops
Kotlin repeat
Kotlin - Ranges
Kotlin - When
Object Oriented Concepts
Classes
Kotlin - Class, Primary and Secondary Constructors
Kotlin - Sealed Classes
Inheritance
Kotlin - Inheritance
Kotlin - Override Method of Super Class
Abstraction
Kotlin - Abstraction
Kotlin - Abstract Class
Kotlin - Interfaces
Data Class
Kotlin - Data Class
Kotlin - Enum Classes
Kotlin - Extension Functions
Kotlin - Null Safety
Exception Handling
Kotlin - Try Catch
Kotlin - Throw Exception
Kotlin - Throw Exception
Kotlin - Custom Exception
Fix Compilation Errors
Kotlin - Variable must be initialized
Kotlin - Primary Constructor call expected
Kotlin - Null can not be a value of a non-null type String
Kotlin - Cannot create an instance of an abstract class
Kotlin - String Operations
Kotlin - Compare Strings
Kotlin - Replace String
Kotlin - Split String
Kotlin - Split String to Lines
Kotlin - String Capitalize
Kotlin - Functions
Kotlin Function - Default Arguments
Kotlin - Use Function
Kotlin - Collections
Kotlin - List
Kotlin List
Kotlin List - forEach
Kotlin - File Operations
Kotlin - Create File
Kotlin - Read Contents of a File
Kotlin - Read Content of a File as list of lines
Kotlin - Write Content to a File
Kotlin - Append Text to a File
Kotlin - Check if File exists
Kotlin - Copy a File to Other
Kotlin - Iterate through all files in a directory
Kotlin - Delete Recursively
Kotlin - Get File Extension
Kotlin - Interview Q/A
Kotlin Interview Questions
Kotlin - Android
Kotlin - Android
Kotlin Android Tutorial
Useful Resources
How to Learn Programming